JVM class 文件结构

class 文件的结构如下:

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结构来表示

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,当前类实现的接口。

fields

field_info的数组:

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的字节码:

Code_attribute {
    u2 attribute_name_index;
    u4 attribute_length;
    u2 max_stack;
    u2 max_locals;
    u4 code_length;
    u1 code[code_length];    //字节码保存在这里
    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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容