jvm原理(27)Java字节码方法表与属性表深度剖析

上一节说到成员变量,这一节说一下方法表
图一:
这里写图片描述
图二:
这里写图片描述
图三:
这里写图片描述
行号00000120 开始就是方法表的开始,刚开始2个字节是方法的数量:00 03 是三个方法(无参构造器、变量a的get和set方法)
方法表:

类型 名称 数量
u2 access_flags 1
u2 name_index 1
u2 descriptor_index 1
u2 attributes_count 1
u2 attributes attributes_count

每一个方法都是这样的一个结构。
00 03后边是 access_flags (00 01)根据图二表示的是public的修饰,name_index:00 07 ,descriptor_index:00 08 在常量池里边是:[ #7 = Utf8 <init>] 、[#8 = Utf8 ()V] ;
然后就是方法的attributes_count 和attributes :
attributes_count :00 01 ,但是attribute_info 的结构是什么呢?为此我们需要知道attribute_info 的结构,如下:
这里写图片描述
attributes_count :00 01 后边的2个字节就是attribute_name_index:00 09(常量池的【#9 = Utf8 Code】).
这里写图片描述
attributes_length: 00 00 00 38 (十进制56)
info:是后面的真正的属性的内容,即方法的字节码。
方法的属性结构:
- JVM预定义了部分attribute,但是编译器自己也可以实现自己的attribute写入class文件
里, 供运行时使用。
- 不同的attribute通过attribute_name_index来区分。
- Codez结构:
code attribute的作用是保存该方法的结构,如所对应的字节码:
Code_attribute{
u2 attribute_name_index; //00 09
u2 attribute_length; // 00 00 00 38
u2 max_stack; //00 02
u2 max_locals; //00 01
u4 code_length; //00 00 00 0A
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];
}
attribute_length: 表示attribute所包含的字节数,不包含attribute_name_index和attribute_lenght字段。
max_stack表示这个方法运行的任何时刻所能达到的操作数栈的最大深度。
max_locals表示方法执行运行期间创建的局部变量的数目,包含用来表示传入的参数的局部变量。
code_length表示该方法所包含的字节码的字节数以及具体的指令码
具体字节码即是该方法被调动时,虚拟机所执行的字节码
exception_table,这里存放的是处理异常的信息
每个exception_table表项由start_pc, end_pc,handler_pc,catch_type组成。
start_pc h=和end_pc表示在code数组中的从start_pc到end_pc处包含start_pc,不包含end_pc)的指令抛出的异常会由这个表项来处理。
handler_pc表示处理异常的代码的开始处,catch_type表示会被处理的异常类型,它指向量池里的一个异常类。当catch_type为0时,表示处理所有的异常。
附加属性
lineNumberTable:这个属性用来表示code数组中的字节码和java代码行数之间的关系。
这个属性可以用来在调试的时候定位代码行的行数。这是属性在调试的时候比较有用,就是抛出异常的代码的行数。
LineNumberTable_attribute{
u2 attribute_name_index;
u4 attribute_length;
u2 line_number_table_length;
{
u2 start_pc;
u2 line_number;
} line_number_table[line_number_table_length]
}

猜你喜欢

转载自blog.csdn.net/wzq6578702/article/details/81415905
今日推荐