带您看懂字节码指令(六):方法调用里有什么

20 阅读10分钟

方法调用里有什么——invokevirtual 为什么要先压 this,#7 又不是偏移量?

前五篇看过帧、空循环、一行加法、指令字节形态和控制流;番外二用递归看过多个帧同时存在的样子。这篇回到第一篇那张“一帧里有什么”的图,把帧怎么来的补上:调用一个新方法时,参数从哪里进入新帧的局部变量表?invokevirtual #7 里的 #7 指向对象内部的某个位置吗?invokestatic 又少了哪一步?

规范 3.6 Receiving Arguments 和 3.7 Invoking Methods 正好回答这两件事。下面先把结论摆出来,再用 javac 21 的真实输出和 demo 的逐步快照核对。

先看结论:

  • 实例方法把 this 放在新帧的 slot 0,参数从 slot 1 开始;静态方法没有 this,参数从 slot 0 开始。
  • invokevirtual 先把接收者 this 压栈,再压实参;调用发生时,这些值从调用者栈弹出,成为被调用帧的 slot 0、slot 1、slot 2。
  • invokevirtual #7 的 #7 是运行时常量池索引,不是对象内部的偏移量;它指向一个 CONSTANT_Methodref 符号引用,运行时才解析成实际方法位置。
  • invokestatic 不需要接收者,所以调用者栈上少压一个 ref:add12and13 的 stack=3,add12and13Static 的 stack=2。
  • ireturn 把被调用帧算出的 int 压回调用者帧的栈,调用者从 invoke 之后那条指令继续。

如果把规范 3.7示例的 addTwo(int i, int j) 再加一个 int k 参数,调用处改成 addTwo(12, 13, 14),实例版和静态版的 stack、locals、args_size 分别变成多少?文末会提供参考答案。

接收参数:this 占 slot 0,静态参数从 slot 0 开始

先把示例代码保存成 ShowCalls.java,方法名和实参都照抄规范 3.6 / 3.7 的 addTwo 与 add12and13 ⬇️

class ShowCalls {
    int addTwo(int i, int j) {
        return i + j;
    }

    static int addTwoStatic(int i, int j) {
        return i + j;
    }

    int add12and13() {
        return addTwo(12, 13);
    }

    static int add12and13Static() {
        return addTwoStatic(12, 13);
    }
}

规范 3.7把静态版也写成 add12and13(),但放在另一个类里;这里为了放进同一个 ShowCalls 类,改名 add12and13Static()。

javac -g ShowCalls.java
javap -v ShowCalls

规范 3.6 的措辞很直接 ⬇️

If n arguments are passed to an instance method, they are received, by convention, in the local variables numbered 1 through n of the frame created for the new method invocation. The arguments are received in the order they were passed.

By convention, an instance method is passed a reference to its instance in local variable 0. In the Java programming language the instance is accessible via the this keyword.

Class (static) methods do not have an instance, so for them this use of local variable 0 is unnecessary. A class method starts using local variables at index 0.

javap -v 的 addTwo 清单 ⬇️

  int addTwo(int, int);
    descriptor: (II)I
    flags: (0x0000)
    Code:
      stack=2, locals=3, args_size=3
         0: iload_1
         1: iload_2
         2: iadd
         3: ireturn

iload_1、iload_2 读的是 slot 1 和 slot 2,slot 0 留给了 this。注意这里有两套计数:args_size=3 数的是参数个数(this + i + j),locals=3 数的是局部变量的 slot 数;这一例刚好都是 3,是因为三个值各占一个 slot。

静态版 addTwoStatic 的清单 ⬇️

  static int addTwoStatic(int, int);
    descriptor: (II)I
    flags: (0x0008) ACC_STATIC
    Code:
      stack=2, locals=2, args_size=2
         0: iload_0
         1: iload_1
         2: iadd
         3: ireturn

flags 多了 ACC_STATIC;iload_0、iload_1 直接读两个参数,this 的位置空出来了。所以 locals 从 3 变成 2,args_size 也少 1。

方法slot 0slot 1slot 2localsargs_size
addTwo(int,int)thisij33
addTwoStatic(int,int)ij—22

发起调用:invokevirtual 先压 this,再压实参

真正调用 addTwo 的是 add12and13() ⬇️

  int add12and13();
    descriptor: ()I
    flags: (0x0000)
    Code:
      stack=3, locals=1, args_size=1
         0: aload_0
         1: bipush        12
         3: bipush        13
         5: invokevirtual #7                  // Method addTwo:(II)I
         8: ireturn

stack=3 是这一节的关键词。aload_0 把 slot 0 的 this 压栈,两个 bipush 再压 12、13;执行到 pc = 5 时,调用者栈上正好三枚值:ref、12、13。这正是规范 3.7的例子,原话是 ⬇️

The invocation is set up by first pushing a reference to the current instance, this, on to the operand stack. The method invocation's arguments ... are then pushed. When the frame for the addTwo method is created, the arguments passed to the method become the initial values of the new frame's local variables. That is, the reference for this and the two arguments, pushed onto the operand stack by the invoker, will become the initial values of local variables 0, 1, and 2 of the invoked method.

也就是说,调用者栈上的三枚值不是留在原地,而是在 invokevirtual 执行时被弹走,依次填进新帧的 slot 0、slot 1、slot 2。新帧的局部变量表已经填好,pc 从 0 开始;调用者则暂停在 pc = 8,等返回值。

invokevirtual 解析前后对比:常量池中的 #7 是符号引用,解析后指向 ShowCalls.addTwo:(II)I

#7 不是偏移量:符号引用什么时候解析

javap 把 #7 注释成 Method addTwo:(II)I,容易让人以为它是对象内部的某个槽位。规范 3.7专门否掉了这种理解 ⬇️

The operand of the invokevirtual instruction (in the example, the run-time constant pool index #4) is not the offset of the method in the class instance. The compiler does not know the internal layout of a class instance. Instead, it generates symbolic references to the methods of an instance, which are stored in the run-time constant pool. Those run-time constant pool items are resolved at run-time to determine the actual method location.

规范例子里是 #4;本文的 ShowCalls 常量池顺序不同,编译出来是 #7,含义一样。

把 ShowCalls.class 的常量池相关几行摘出来 ⬇️

   #7 = Methodref          #8.#9          // ShowCalls.addTwo:(II)I
   #8 = Class              #10            // ShowCalls
   #9 = NameAndType        #11:#12        // addTwo:(II)I
  #10 = Utf8               ShowCalls
  #11 = Utf8               addTwo
  #12 = Utf8               (II)I

#7 是 CONSTANT_Methodref,它本身不写方法地址,而是拆成两层引用:#8 给出类 ShowCalls,#9 给出名字 addTwo 和描述符 (II)I。javac 只知道这些符号,真正的类布局和方法位置要等运行时解析。

方法调用时常量池中的 CONSTANT_Methodref 与解析结果

解析发生在第一次执行到 invokevirtual 时,而不是编译期;解析结果会缓存,后续调用直接复用。解析完成后,调用者栈上的 ref/12/13 被弹出,被调用帧的 slot 0/1/2 就有了初值 ⬇️

invokevirtual 调用时两层帧的变化:被调用帧在上、调用者在下,调用者暂停,被调用帧接收 this、12 和 13

注意颜色约定:蓝色是本步写入或压入的值,浅蓝色是此前已有的值,琥珀色边框是本步读取的局部变量 slot。这里 iload_1 正在读 slot 1,所以那一格是琥珀色边框。

被调用帧执行 iload_1、iload_2、iadd、ireturn,最后一步把 25 压回调用者栈 ⬇️

被调用方法 ireturn 后,结果 25 回到调用者帧的栈顶

把这条路径按时间串起来 ⬇️

一次 invokevirtual 的时序:caller 解析常量池 7 号项,创建 addTwo 帧,ireturn 把 25 压回调用者

时序图的 mermaid 源码见 method-call-sequence.mmd。

invokestatic:少一个 this,参数整体前移一位

静态版的调用者清单如下 ⬇️

  static int add12and13Static();
    descriptor: ()I
    flags: (0x0008) ACC_STATIC
    Code:
      stack=2, locals=0, args_size=0
         0: bipush        12
         2: bipush        13
         4: invokestatic  #13                 // Method addTwoStatic:(II)I
         7: ireturn

和 add12and13 对照,少了 aload_0,stack 从 3 降到 2;常量池里的 #13 同样是 Methodref ⬇️

  #13 = Methodref          #8.#14         // ShowCalls.addTwoStatic:(II)I
  #14 = NameAndType        #15:#12        // addTwoStatic:(II)I
  #12 = Utf8               (II)I

#8 仍是 ShowCalls,#12 仍是描述符 (II)I,只有名字从 addTwo 换成 addTwoStatic。invokestatic 执行时,调用者栈上的 12、13 弹出,成为 addTwoStatic 帧的 slot 0、slot 1——没有 this,所以整体前移一位 ⬇️

invokestatic 调用时没有 this,被调用帧在上、调用者在下,12 和 13 落到被调用帧的 slot 0 和 slot 1

规范 3.7对这点的原话是 ⬇️

Compiling an invocation of a class (static) method is very much like compiling an invocation of an instance method, except this is not passed by the invoker. The method arguments will thus be received beginning with local variable 0 (§3.6). The invokestatic instruction is always used to invoke class methods.

调用者指令压栈顺序invoke 操作数被调用帧 locals调用者 stack
add12and13ref, 12, 13#7 → addTwo:(II)Ithis, 12, 133
add12and13Static12, 13#13 → addTwoStatic:(II)I12, 132

配套 demo

配套的 MethodCallDemo.java 是一个 Swing 窗口,下拉框切换 add12and13 和 add12and13Static 两个示例。下载后运行(需 JDK 16+,用到了 record;本文用 JDK 21)⬇️

javac MethodCallDemo.java
java MethodCallDemo

窗口分四块 ⬇️

  • 左上:ShowCalls.java 源码,当前执行的方法体高亮
  • 左下:调用者与被调用者的解码指令,列出字节偏移、原始字节、助记符和作用
  • 右上:常量池中的 CONSTANT_Methodref,以及「未解析 / 已解析」状态
  • 右下:两层帧的局部变量表(slot)和操作数栈(unit);按调用栈画法,调用者在下、被调用者在上

文章里的截图用无界面模式导出 ⬇️

java MethodCallDemo --render img
java MethodCallDemo --window img

一个容易看漏的细节:被调用帧运行时,调用者帧并没有消失,而是停在 invoke 的下一条指令(pc = 8 的 ireturn)之前。demo 里它的状态标成 paused;ireturn 把结果压回调用者栈顶后,状态才变成 resumed。

数字对照

数字 / 指令含义出处
stack=3 / locals=1接收者 + 两个实参同时在调用者栈上add12and13
stack=2 / locals=0静态调用不压 thisadd12and13Static
args_size=3 / locals=3参数个数与 slot 数相等:三个值各占一个 slotaddTwo
args_size=2 / locals=2静态方法没有 this,两项都少 1addTwoStatic
invokevirtual #7#7 是 CONSTANT_Methodref 索引,运行时解析规范 3.7
invokestatic #13不传接收者,参数从被调用帧 slot 0 开始规范 3.7

动手题:再加一个 int 参数

把 addTwo(int i, int j) 改成 addTwo(int i, int j, int k),调用处改成 addTwo(12, 13, 14),重新 javap -v 后:

  • addTwo 的 stack、locals、args_size 分别是多少?
  • 实例版调用者的 stack 是多少?静态版呢?
  • 常量池里会出现新的 NameAndType 吗?

参考答案:

  • 实例版 addTwo:stack=2、locals=4、args_size=4;调用者 add12and13 的 stack=4。
  • 静态版 addTwoStatic:stack=2、locals=3、args_size=3;调用者 add12and13Static 的 stack=3。
  • 三个 int 求和仍是两两上栈,stack 不会变成 3。
  • 会,常量池里新增一条 NameAndType(addTwo:(III)I)和一条 Utf8((III)I);addTwo 名字的 Utf8 复用。具体编号由 class 自己的常量池决定。

小结

  1. 接收者先压栈,参数随后:invokevirtual 用 aload_0 把 this 压到栈底,再压实参;这些值在调用发生时弹出,成为被调用帧的 slot 0/1/2。
  2. 静态方法不传 this:invokestatic 少一次 aload_0,调用者 stack 峰值少 1,被调用帧参数从 slot 0 开始。
  3. args_size 和 locals 不是一回事:前者数参数个数(含 this),后者数 slot;两个 int 参数加 this 时刚好都是 3。
  4. #7 是符号引用:CONSTANT_Methodref 由「类 + 名字 + 描述符」组成,编译器不知道对象内部布局,运行时才解析出实际方法位置。
  5. ireturn 完成交接:被调用帧的结果压回调用者栈顶,调用者从 invoke 的下一条指令继续。

new + dup + invokespecial <init> 那条构造器路径属于规范 3.8,本篇不展开。

系列导航:

顺序标题核心内容
一一帧里有什么帧、局部变量表、操作数栈
二空循环里有什么spin 循环里的 i++ 与循环条件
三一行加法里有什么表达式如何展开成多条指令
四一条指令里有什么单条指令的字节形态
五控制流里有什么while 判断位置、double 比较、NaN
六方法调用里有什么(本篇)参数接收、invokevirtual / invokestatic、符号引用解析
番外一用 Swing 重做操作数栈演示iconst/iadd/isub 的单步演示
番外二递归里有什么多层帧、等待中的操作数栈、返回传播

参考资料