Java Generics Type Erasure byte code

前端 未结 4 1333
情话喂你
情话喂你 2021-01-04 06:32

As per the java documentation on Erasure of Generic Types,

Consider the following generic class that represents a node in a singly linked list:

publ         


        
4条回答
  •  轮回少年
    2021-01-04 07:19

    The fact that the class is generic is retained. For instance, at runtime you can call

    Node.class.getTypeParameters()
    

    The next bit of code will return "T".

    (new Node()).getClass().getTypeParameters()[0].getName()
    

    You can't get the value of type parameters at runtime, but the JVM knows they're there.

    Erasure comes into play when you construct a instance.

    Node node = new Node(1, null);
    Integer i = node.getData();
    

    Becomes

    Node node = new Node(1, null);
    Integer i = (Integer)node.getData();
    

    Generic classes are always generic. But instances do not carry generic type information inside them. The compiler verifies that everything you've done agrees with the generic type and then inserts casts.

提交回复
热议问题