Where are generic types stored in java class files?

前端 未结 2 834
生来不讨喜
生来不讨喜 2020-11-28 10:46

I am well aware that generic types are erased from Java code when it is compiled. What information (attributes?) do 1.5+ JVMs use to implement getGenericType ,

2条回答
  •  执笔经年
    2020-11-28 11:31

    They are stored in Signature attributes; see section 4.8.8 of the updated Java Virtual Machine Specification, as well as section 4.4.4 for the format of the field type signature.

    Here's an example using javap -verbose java.util.Map:

    public interface java.util.Map
      SourceFile: "Map.java"
      Signature: length = 0x2
       00 1E 
      [other attributes omitted]
    

    The Signature attribute here specifies (if you read this as big-endian, like all integer quantities in the JVM class file format are) constant pool value #30 (30 = 0x1E). So let's have a look there:

    const #30 = Asciz       Ljava/lang/Object;;
    

    Read this in the context of the grammar specified in 4.4.4. So, this uses two type parameters, K extends java.lang.Object and V extends java.lang.Object. The type itself (Map) also extends class java.lang.Object, and no interfaces.

提交回复
热议问题