简体   繁体   English

如何在Java运行时设置通用类型

[英]How to set generic type at runtime in java

I saw some questions like this but different from my case.I want to set generated class at build time as generic type at runtime. 我看到了类似这样的问题,但与我的情况不同:我想在构建时将生成的类设置为运行时的泛型类型。 here is code. 这是代码。

  //employee class is generated at build time 
  void function(Class<?> employee)
  {  
      // I want to set class as generic type like this 
     List<employee> emps= new ArrayList<employee>(employee);
   }

how to do this? 这个怎么做?

You can't. 你不能

Generics are all mapped to java.lang.Object on compilation by a process called type erasure . 泛型全部在编译时通过称为类型擦除的过程映射到java.lang.Object

You can only build things that are checked at compile time: consider using Class<? extends ...> 您只能构建在编译时检查的内容:考虑使用Class<? extends ...> Class<? extends ...> notation. Class<? extends ...>表示法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM