Cannot Create Instances of Type Parameters
You'll learn why you can't write new T() in generic code and how type erasure makes runtime instantiation impossible.
The Problem with new T()
When you write a generic class or method, you might naturally try to create an instance of your type parameter:
public class Container<T> {
private T item;
public void createItem() {
// Compile error: Cannot instantiate the type T
item = new T(); // ❌ Illegal!
}
}
This won't compile. But why?
Type Erasure Strikes Again
Remember that type parameters are erased at runtime. The JVM doesn't know what T actually is—it becomes Object (or the bound you specified) after compilation.
To create an object with new, the JVM needs to know:
- Which constructor to call
- How much memory to allocate
- What type-specific initialization to perform
Since T doesn't exist at runtime, none of this information is available. It's like asking someone to build you a vehicle without telling them whether it's a car, boat, or bicycle.
Common Workarounds
You'll need to pass type information explicitly:
-
Pass a
Class<T>object (type token):public Container(Class<T> clazz) throws Exception { item = clazz.getDeclaredConstructor().newInstance(); } -
Use a factory (supplier pattern):
public Container(Supplier<T> factory) { item = factory.get(); }
Both approaches work around erasure by providing runtime type information the compiler can't supply automatically.
Key Takeaway: You cannot write new T() because type erasure removes all type parameter information at runtime, leaving the JVM unable to determine which actual class to instantiate. Use type tokens or factory patterns instead.