Create instance of generic type in Java?

后端 未结 27 3108
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 06:14

Is it possible to create an instance of a generic type in Java? I\'m thinking based on what I\'ve seen that the answer is no (due to type erasure), but

27条回答
  •  天涯浪人
    2020-11-21 06:48

    From Java Tutorial - Restrictions on Generics:

    Cannot Create Instances of Type Parameters

    You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:

    public static  void append(List list) {
        E elem = new E();  // compile-time error
        list.add(elem);
    }
    

    As a workaround, you can create an object of a type parameter through reflection:

    public static  void append(List list, Class cls) throws Exception {
        E elem = cls.newInstance();   // OK
        list.add(elem);
    }
    

    You can invoke the append method as follows:

    List ls = new ArrayList<>();
    append(ls, String.class);
    

提交回复
热议问题