Class 文件格式总览
classFile
ClassFile{
u4 magic; 魔数固定值 0xCAFEBABE
u2 minor_version; class小版本信息
u2 major_version;
u2 constant_pool_count;
cp_info contant_pool[constant_pool_count-1];
u2 access_flags;访问权限 private public
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[method_count];
u2 attributes_count;
attribute_info attributes[attributes_count]; attributes_info 结构体
}
常量池及相关内容
Constant pool一共14种类型
cp_info{
u1 tag;
u1 info[];伪代码
}
CONSTANT_UTF8 和 CONSTANT_STRING 的区别
CONTANT_UTF8 存储的是字符串的内容
CONTANT_String 常量项的索引
_index记录的都是字符索引,为了减少存储空间
信息描述规则
字符串描述成员变量,成员函数
数据类型
原始数据的对应的字符描述 为 B C D F I J S Z 类型分别为byte char double float int long short boolean
引用的数据类型 LClassName; 使用/代替. 必须带;
数组也是一种引用类型 数组是用[来表示 [LClassName;
成员变量描述 Field Description
FieldType BaseType | ObjectType|ArrayType
[ComponentType FieldType
成员函数描述规则 Method Descriptor
(ParameterDescriptor*) ReturnDescriptor
field_info method_info
fileld_info{
u2 access_flags;
u2 name_index;
u2 descriptior_index;
u2 attributes_count;
attribute_info attributes[attributes_count];
}
method_info{
u2 access_flags;
u2 name_index;
u2 descriptior_index;
u2 attributes_count;
attribute_info attributes[attributes_count];
}
access_flages;
Class Field Method 都存在这些访问标志
Field 比较特殊的有 ACC_TRANSIENT 表明该成员不能被串行化
ACC_SYNTHETIC 表明编译器根据情况生成,源码里无法定义这样的成员
属性介绍
attribute_info{
u2 attribute_name_index;//指向UTF-8字符
u4 attribute_length; //下面属性的长度
u1 info[attribute_length]; //具体内容
}
属性名称:
Code 只出现在method中,描述一个非native和abstract的函数内容,对应函数内容对应的虚拟机指令
ConstantValue 只出现在field_info 中,同于描述一个成员域(long float double int short char byte boolean String) 等
Exception 当一个函数抛出异常或错误的时候,函数的method_info 方法会保存此属性。
SourceFile 此属性包含一个指向UTF8常量的索引,包含class对应的源码文件名称
LocalVariableTable 属性可以包含属性。包含在Code中,此属性是用来描述一个本地变量相关的信息。代码在源码的哪一行。
Code属性
Code_attribute{
u2 attribute_name_index;
u2 attribute_lenght;
u2 max_stack;
u2 max_locals;
u4 code_length;
u1 code[code_lengh];
u2 exception_table_length;{
u2 stack_pc; 所有的pc都包含在code数组内,且表示try/catch是从哪一个语句开始的
u2 end_pc; // 只包含try 不包含catcj
u2 handler_pc; // 表示catch是从哪句话开始的
u2 catch_type; //表示catch中exception的名字,指向utf-8的常量项。比如catch_type 取值为0 则她表示final{}语句块
}excpetion_table[exception_table_length];
u2 attributes_count;
attribute_info attributes[attributes_count];
}
Code_attributes 还包含别的属性:
LineNumberTable 用于调试,指明哪条指令,对应源码哪一行
LocalVariaTable 用于调试,调试时可以用于计算本地的变量值
LocalVariableTable 功能和LocalVariaTable
StackMapTable java1.6以上才支持的属性,用于校验
LineNumberTable属性
LineNumberTable_attribute{
u2 attribute_name_index;
u4 attribute_lengh;
u2 line_number_table_lengh; {
u2 start_pc;
u2 line_number;
} line_number_table[line_number_table_lengh];
}
LocalVariaTable
LocalVariaTable_attribute{
u2 attribute_name_index;
u4 attribute_lengh;
u2 local_variable_table_lengh;{
u2 start_pc;
u2 lengh;
u2 name_index;
u2 descriptor_index;
u2 index;
}local_variable_table[local_variable_table_length];
}