Create instance of generic type in Java?

后端 未结 27 3101
佛祖请我去吃肉
佛祖请我去吃肉 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:55

    Java unfortunatly does not allow what you want to do. See the official workaround :

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

提交回复
热议问题