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 want
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);
Like this (cast to the Class
raw type first):
@SuppressWarnings({ "unchecked", "rawtypes" })
Class<List<MyType>> clazz = (Class) List.class