In Java, why is there no generic type info at run time?

You have "overlooked a simple concept". The generics exist only at compile time, and only to enforce things like parametric polymorphism. Because the folks who implemented them decided that developers should be able to use them (generics) and still deploy their built artifacts to targets with older JVMs (an extremely questionable decision in my mind, as the runtime libraries also changed between 1.4 and 1.5), they had the compiler decide if everything type-checks and then they throw away almost all of that information before creating the compiled artifact.

I say almost all of that information because in some special cases it is still around at runtime.


The problem is that generics was not always present in java (I think they added it in 1.5). So in order to be able to achieve backwards compatibility there is type erasure which effectively erases generic type information while compiling your code in order to achieve that goal.

Excerpt from the relevant parts of the official documentation:

During the type erasure process, the Java compiler erases all type parameters and replaces each with its first bound if the type parameter is bounded, or Object if the type parameter is unbounded.

So this code for example

public class Node<T extends Comparable<T>> {

    private T data;
    private Node<T> next;

    public Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    }

    public T getData() { return data; }
    // ...
}

becomes this after type erasure:

public class Node {

    private Comparable data;
    private Node next;

    public Node(Comparable data, Node next) {
        this.data = data;
        this.next = next;
    }

    public Comparable getData() { return data; }
    // ...
}

There is a way however to resurrect some of that type information if you tread the path of reflection which is like a lightsaber: powerful but also dangerous.

Tags:

Java

Generics