Instantiating a generic type

suggest change

Due to type erasure the following will not work:

public <T> void genericMethod() {
    T t = new T(); // Can not instantiate the type T.
}

The type T is erased. Since, at runtime, the JVM does not know what T originally was, it does not know which constructor to call.


Workarounds

  1. Passing T’s class when calling genericMethod:
public <T> void genericMethod(Class<T> cls) {
    try {
        T t = cls.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
         System.err.println("Could not instantiate: " + cls.getName());
    }
}
genericMethod(String.class);

newInstance needs an accessible no-arg constructor. String.class has one, so that call succeeds. A class without one throws InstantiationException at runtime. Class.newInstance is deprecated since Java 9; cls.getDeclaredConstructor().newInstance() is the replacement.

  1. Passing a reference to T’s constructor:
public <T> void genericMethod(Supplier<T> cons) {
    T t = cons.get();
}
genericMethod(String::new);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents