Java Generics Pass .class Reference

前端 未结 2 417
暖寄归人
暖寄归人 2021-01-05 01:15

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

相关标签:
2条回答
  • 2021-01-05 01:28

    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);
    
    0 讨论(0)
  • 2021-01-05 01:34

    Like this (cast to the Class raw type first):

    @SuppressWarnings({ "unchecked", "rawtypes" })
    Class<List<MyType>> clazz = (Class) List.class
    
    0 讨论(0)
提交回复
热议问题