Type Tokens and Reification Workarounds
What You'll Learn
You'll learn how passing Class<T> objects as method parameters gives you runtime access to type information that erasure would otherwise destroy.
The Problem: Missing Type Information
Because of type erasure, type parameters vanish at runtime. If you write a method like <T> T create(), the runtime has no idea what T actually is—it becomes Object. This makes it impossible to create instances or check types dynamically.
The Solution: Type Tokens
A type token is a Class<T> object passed explicitly to preserve type information. Instead of relying on the erased type parameter alone, you pass the actual class object:
public <T> T create(Class<T> clazz) throws Exception {
return clazz.newInstance(); // Runtime knows the real type!
}
// Usage:
String str = create(String.class);
Integer num = create(Integer.class);
Here, String.class and Integer.class are type tokens—they carry runtime type information that survives erasure.
Why It Works
The Class<T> parameter provides two benefits:
- Runtime type access: You can call
clazz.newInstance(),clazz.isInstance(), orclazz.cast()with the actual type - Type-safe return: The compiler knows the return type matches
T
Real-World Pattern
This pattern appears frequently in frameworks and libraries where you need to instantiate generic types:
public <T> List<T> createList(Class<T> elementType) {
List<T> list = new ArrayList<>();
// Could use elementType for validation, reflection, etc.
return list;
}
Key Takeaway: Type tokens (Class<T> parameters) are the standard workaround for type erasure, providing runtime access to type information that type parameters alone cannot deliver.