user3270407 user3270407 - 20 days ago 6
Java Question

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

Consider this example taken from a book, with a super class Gen and a subclass Gen2...

class Gen<T> { }

class Gen2<T> extends Gen<T> { }


Now the book states following will not compile (lets assume its in a main method)

Gen2<Integer> obj = new Gen2<Integer>();

if (obj instanceof Gen2<Integer>) {

//do something
}


This can't be compiled because generic type info does not exist at runtime. If it doesn't exist at runtime, when does it exist? I thought that it would not exist at compile time, but would exist at runtime. Certainly, the following works for runtime with a wildcard...

if (obj instanceof Gen<?>) {

//do something else

}


So to clarify, my question is why does generic type info not exist at runtime? Have I overlooked a simple concept?

Answer

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.

Comments