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

Which throws exceptions, since there is no way to know if the passed class has an accessible default constructor.
  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