简体   繁体   中英

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 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> . It will accept Boolean objects. 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:

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).

   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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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