Java Generics Pass .class Reference

前端 未结 2 432
暖寄归人
暖寄归人 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, 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 collectionClass, Class elementClass, int number) {
        Collecton c = (Collection) collectionClass.newInstance();
        for(int i=0;i list = createCollection(ArrayList.class, MyType.class, 100);
    

提交回复
热议问题