Course contentsShow
← Java
Lesson 898 of 2,87021. Generics FundamentalsFree lesson

Type Tokens and Reification Workarounds

Exploring how passing Class<T> as a parameter allows runtime access to type information despite erasure.

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:

  1. Runtime type access: You can call clazz.newInstance(), clazz.isInstance(), or clazz.cast() with the actual type
  2. 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.