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

后端 未结 3 1969
悲&欢浪女
悲&欢浪女 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 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> {
    
        private T data;
        private Node next;
    
        public Node(T data, Node 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.

提交回复
热议问题