简体   繁体   English

将泛型作为参数传递给Java?

[英]Passing generic type as a parameter in java?

Is it possible to save a Type in a variable, 是否可以将类型保存在变量中,
in order to instantiate a List of this type? 为了实例化此类型的列表?

//something like that
Type type = Boolean;
List<type> list = new List<type>();
list.add(true);

For the first requirement, you are looking for Class : 对于第一个要求,您正在寻找Class

Class type = Boolean.class;

However, I don't think the seconds requirement is feasible, since generic types only exist at compile time: 但是,我认为秒数要求不可行,因为通用类型仅在编译时存在:

List<type> list = new List<type>(); // invalid code

You can, however, work with List<Object> . 但是,您可以使用List<Object> It will accept Boolean objects. 它将接受Boolean对象。 Whether this will buy you anything untlimately depends on your use case. 这是否会给您带来任何好处,取决于您的用例。

Generic is a compile time feature, not run time, so you cannot use variable to determine the generic type, even using NPE's note (using Class ) will not compile: 泛型是一种编译时功能,而不是运行时,因此,即使使用NPE的注释(使用Class )也无法编译,所以无法使用变量来确定泛型类型:

Class<?> type = Boolean.class;
// can't do that...
List<type> list = new List<type>();
list.add(true);

In second case why do you want to use generics when type is unknown? 在第二种情况下,为什么要在类型未知的情况下使用泛型? You can better use non-generic arraylist ( used before jdk 5). 您可以更好地使用非通用arraylist(在jdk 5之前使用)。

   List a = new ArrayList();
   a.add(object);

This style is still supported by higher versions and even generics style gets converted to this form after compilation. 更高版本仍支持此样式,甚至在编译后将泛型样式转换为此形式。 You will get warning in above code which you can suppress. 您将在上面的代码中收到警告,可以取消显示。

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

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