I need to call a super constructor that requires me to pass a .class
reference of a generic type. How can I achieve this with Java?
The constructor wants to have..
Class<List<MyType>>
As generics are erased at runtime, I have no clue how to satisfy the constructor.
List<MyType>.class // does not work ;-)
We use generics wildcard (?) with super keyword and lower bound class to achieve this. We can pass lower bound or any supertype of lower bound as an argument, in this case, java compiler allows to add lower bound object types to the list.
To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.
If we want the data to be of int type, the T can be replaced with Integer, and similarly for String, Character, Float, or any user-defined type. The declaration of a generic class is almost the same as that of a non-generic class except the class name is followed by a type parameter section.
Like this (cast to the Class
raw type first):
@SuppressWarnings({ "unchecked", "rawtypes" })
Class<List<MyType>> clazz = (Class) List.class
You can't call the constructor for List<MyType>
, in fact you can't call the constructor for List
as its an interface. What you can do is call the constructor for ArrayList.class
and also pass the type of the elements you expect.
public C createCollection(Class<? extends Collection> collectionClass, Class elementClass, int number) {
Collecton c = (Collection) collectionClass.newInstance();
for(int i=0;i<number;i++)
c.add(elementClass.newInstance());
return (C) c;
}
List<MyType> list = createCollection(ArrayList.class, MyType.class, 100);
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