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