Java字节码整体结构
如图
- 大致如图
- 进一步
Class字节码中有两种数据类型
- 字节数据直接量 : 这是基本的数据类型。共细分为u1、u2、u4、u8四种,分别代表连续的1个字节、2个字节、4个字节、8个字节组成的整体数据。
- 表(数组) : 表是由多个基本数据或其他表,按照既定顺序组成的大的数据集合。表是有结构的,它的结构体现在:
- 组成表的成分所在的位置和顺序都是已经严格定义好的。
Access_Flag访问标志
- 常量池完了,后面就是 Access_Flag访问标志
- 访问标志信息包括该Class文件是类还是接口,是否被定义成public,是否是abstract,如果是类,是否被声明成final。通过上面的源代码,我们知道该文件是类并且是public。
value是十六进制,上面表格漏了private 其value是0x0002。
field字段表结构
在field_count之后有(field_info)字段表,结构如下
field_info {
u2 access_flags;
u2 name_index; //索引去常量池找
u2 descriptor_index; //索引去常量池找
u2 attributes_count; //没有就是00 00
attribute_info attributes[attributes_count];//属性表
}
- attribute_info又有它的结构
attribute_info {
u2 attribute_name_index;
u4 attribute_length;
u1 info[attribute_length];
}
method方法表结构
在method_count之后有(method_info)字段表,结构如下
method_info {
u2 access_flags;
u2 name_index;
u2 descriptor_index;
u2 attributes_count;
attribute_info attributes[attributes_count];
}
- 方法中的每个属性都是一个attribute_info结构
attribute_info {
u2 attribute_name_index;
u4 attribute_length;
u1 info [attribute_length];
}
在attribute中有code_attribute
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];
}
- code属性差不多就是字节码指令
对于Java的实例方法,里面必有一个为this的局部变量。
小结
阅读字节码
- 只要知道字节码的结构,以及每个结构所占的字节数,就可以阅读字节码的内容了。
- 当然除了要知道字节码的结构,还要知道每个项的含义。