简体   繁体   中英

Java Generics Pass .class Reference

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

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

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