Instantiating a generic type
suggest changeDue 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
- Passing
T’s class when callinggenericMethod:
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.
- Passing a reference to
T’s constructor:
public <T> void genericMethod(Supplier<T> cons) {
T t = cons.get();
}
genericMethod(String::new);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents