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);
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With