字节码执行

208 阅读2分钟

局部变量

A single local variable can hold a value of type boolean, byte, char, short, int, float, reference, or returnAddress. A pair of local variables can hold a value of type long or double.

一个局部变量可以存一个 boolean / byte / char / short / int / float / 引用 / 返回地址。

两个局部变量何以存一个 long / double。

java代码
public class C {
    public int test(int a, long b) {
        int b2 = (int) b;
        int sum = a + b2;
        return sum;
    }
}
test方法栈帧的局部变量表
+--------+
|  this  |   0   实例方法(非静态)的局部变量表,下标为0的元素是该类的this对象
+--------+
|   a    |   1
+--------+
|   b    |   2
+--------+
|   b    |   3   (b是long类型,占用2和3两个局部变量)
+--------+
|   b2   |   4
+--------+
|  sum   |   5
+--------+
字节码
int b2 = (int) b;   Code 0,1,2
int sum = a + b2;   Code 4,5,7,8
return sum;         Code 10,12
 
  public int test(int, long);   // 局部变量表(local variable array)的下标为0的是this,1是int,2和3是long(没有限定大端格式还是小端格式)
    Code:
       0: lload_2               // 把局部变量表[2,3]中的long压入操作数栈(operand stack)              加载b           执行后,栈中1个long,占2个slot
       1: l2i                   // code 0 压入的long出栈,将该long转化为int,将得到的int压入操作数栈   执行(int)b       执行后,栈中1个int,占1个slot
       2: istore        4       // 操作数栈中int出栈,将该int存入变量b2中                            b2=(int)b       执行后,栈为空
       4: iload_1               // 把局部变量表[1]中的int,压入操作数栈                              加载a            执行后,栈中1个int,占1个slot
       5: iload         4       // 把局部变量表[4]中的int,压入操作数栈                              加载b2           执行后,栈中2个int,占1个slot
       7: iadd                  // 操作数栈出栈2个int,将该2个int相加,和压入操作数栈                  计算a+b2         执行后,栈中1个int
       8: istore        5       // 操作数栈中int出栈,将该int存入变量sum中                           sum=a+b2        执行后,栈为空
      10: iload         5       // 把局部变量表[5]中的int,压入操作数栈                              加载sum          执行后,栈中1个int
      12: ireturn               // 操作数栈中int出栈,将该出栈的int返回                              return sum      执行后,栈为空