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

后端 未结 3 1958
悲&欢浪女
悲&欢浪女 2020-12-16 05:10

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

class Gen { }

class Gen2 extends Gen { }
<         


        
相关标签:
3条回答
  • 2020-12-16 05:49

    Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. [...] Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

    I don't think this is related to backwards compatibility at all. If you compile your code targetting 1.5 or more, the code will be not compatible with 1.4, regardless the use of generics.

    0 讨论(0)
  • 2020-12-16 05:55

    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.

    0 讨论(0)
  • 2020-12-16 06:04

    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.

    0 讨论(0)
提交回复
热议问题