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

Type Parameters Become Object

Seeing how unbounded type parameters like <T> are replaced with Object in bytecode, affecting runtime type information.

Type Parameters Become Object

You'll learn how Java's compiler replaces unbounded generic type parameters with Object behind the scenes.

When you write generic code with a type parameter like <T>, the Java compiler performs a trick called type erasure. For unbounded type parameters (those without any constraints), the compiler replaces every occurrence of T with Object in the bytecode.

How It Works

Imagine you write a generic class:

public class Box<T> {
    private T item;
    
    public void set(T item) {
        this.item = item;
    }
    
    public T get() {
        return item;
    }
}

After type erasure, the bytecode looks roughly like this:

public class Box {
    private Object item;  // T became Object
    
    public void set(Object item) {  // T became Object
        this.item = item;
    }
    
    public Object get() {  // T became Object
        return item;
    }
}

Runtime Implications

This transformation has important consequences:

  • No runtime type information: At runtime, Box<String> and Box<Integer> are both just Box containing Object references
  • Type safety happens at compile-time: The compiler inserts casts where needed, but the bytecode has no memory of what T was
  • Cannot check type parameters: You can't write if (item instanceof T) because T doesn't exist at runtime—only Object does

Think of it like a shipping container labeled "fragile" on the outside. Once it's loaded on the ship, all the crew sees is a generic container. The "fragile" information helped during loading (compile-time) but isn't visible during transport (runtime).

Key Takeaway: Unbounded type parameters like <T> are replaced with Object in bytecode, meaning generics exist only at compile-time for type checking, not at runtime.