Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are generic types stored in java class files?

Tags:

java

jvm

generics

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 , etc. ?

like image 643
Joe Avatar asked Jun 02 '09 04:06

Joe


People also ask

Where are the class files stored in Java?

The class files actually reside as jar files inside the Java distribution being used. Most files are in rt. jar (runtime).

What is generic type class in Java?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.

How do you declare a generic type in a class?

A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.


1 Answers

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       <K:Ljava/lang/Object;V:Ljava/lang/Object;>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.

like image 91
Chris Jester-Young Avatar answered Oct 02 '22 06:10

Chris Jester-Young