Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing generic type as a parameter in java?

Tags:

java

generics

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);
like image 460
Skip Avatar asked Nov 27 '12 08:11

Skip


People also ask

How do you declare a generic parameter in Java?

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound.

Is generic type parameter?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

Can you declare a variable with a generic type?

Yes it is possible, but only for Functions, not any arbitrary variable. As you can see, it's the type itself, where you define generics and then you can make a variable of that type, which allows it to set the generic.


1 Answers

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.

like image 188
NPE Avatar answered Oct 28 '22 22:10

NPE