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.
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.
Passing a reference to T
's constructor:
public <T> void genericMethod(Supplier<T> cons) {
T t = cons.get();
}
genericMethod(String::new);