class 文件的結(jié)構(gòu)如下:
ClassFile {
u4 magic;
u2 minor_version;
u2 major_version;
u2 constant_pool_count;
cp_info contant_pool[constant_pool_count – 1];
u2 access_flags;
u2 this_class;
u2 super_class;
u2 interfaces_count;
u2 interfaces[interfaces_count];
u2 fields_count;
field_info fields[fields_count];
u2 methods_count;
method_info methods[methods_count];
u2 attributes_count;
attribute_info attributes[attributes_count];
}
Constant Pool
每個Constant Pool Entry由cp_info結(jié)構(gòu)來表示
cp_info {
u1 tag;
u1 info[];
}
tag 表示constant type:
Constant Type | Value |
---|---|
CONSTANT_Class | 7 |
CONSTANT_Fieldref | 9 |
CONSTANT_Methodref | 10 |
CONSTANT_InterfaceMethodref | 11 |
CONSTANT_String | 8 |
CONSTANT_Integer | 3 |
CONSTANT_Float | 4 |
CONSTANT_Long | 5 |
CONSTANT_Double | 6 |
CONSTANT_NameAndType | 12 |
CONSTANT_Utf8 | 1 |
CONSTANT_MethodHandle | 15 |
CONSTANT_MethodType | 16 |
CONSTANT_InvokeDynamic | 18 |
不同tag對應的info[]不同。
類的屬性
access_flags :類的訪問屬性
this_class:index to constant pool,指向一個CONSTANT_Class_info。當前類
super_class:index to constant pool(0或者valid index),指向一個CONSTANT_Class_info。當前類的父類
interface
interfaces:index to constant pool,指向一個CONSTANT_Class_info,當前類實現(xiàn)的接口。
fields
field_info的數(shù)組:
field_info {
u2 access_flags;
u2 name_index; //index to constant pool, field的name
u2 descriptor_index; //index to constant pool, field的type
u2 attributes_count;
attribute_info attributes[attributes_count];
}
methods
method_info {
u2 access_flags;
u2 name_index;
u2 descriptor_index;
u2 attributes_count;
attribute_info attributes[attributes_count];
}
method_info中的attribute_info包括:Code , Exceptions , Synthetic , Signature , Deprecated , RuntimeVisibleAnnotations , RuntimeInvisibleAnnotations , RuntimeVisibleParameterAnnotations , RuntimeInvisibleParameterAnnotations , AnnotationDefault
其中Code attribute_info包含了method的字節(jié)碼:
Code_attribute {
u2 attribute_name_index;
u4 attribute_length;
u2 max_stack;
u2 max_locals;
u4 code_length;
u1 code[code_length]; //字節(jié)碼保存在這里
u2 exception_table_length;
{ u2 start_pc;
u2 end_pc;
u2 handler_pc;
u2 catch_type;
} exception_table[exception_table_length];
u2 attributes_count;
attribute_info attributes[attributes_count];
}
attributes
包含了當前class的一些attribute_info
Reference:
https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html