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

方法调用里有什么------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 ⬇️

java 复制代码
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(),字节码形状不变。

bash 复制代码
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 清单 ⬇️

text 复制代码
  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 的清单 ⬇️

text 复制代码
  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 0 slot 1 slot 2 locals args_size
addTwo(int,int) this i j 3 3
addTwoStatic(int,int) i j --- 2 2

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

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

text 复制代码
  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,等返回值。

#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.

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

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

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

解析发生在 invokevirtual 执行时,而不是编译期。解析完成后,调用者栈上的 ref/12/13 被弹出,被调用帧的 slot 0/1/2 就有了初值 ⬇️

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

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

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

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

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

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

text 复制代码
  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 ⬇️

text 复制代码
  #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,所以整体前移一位 ⬇️

规范 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
add12and13 ref, 12, 13 #7 → addTwo:(II)I this, 12, 13 3
add12and13Static 12, 13 #13 → addTwoStatic:(II)I 12, 13 2

配套 demo

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

bash 复制代码
javac MethodCallDemo.java
java MethodCallDemo

窗口分四块 ⬇️

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

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

bash 复制代码
java MethodCallDemo --render img
java MethodCallDemo --window img

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

数字对照

数字 / 指令 含义 出处
stack=3 / locals=1 接收者 + 两个实参同时在调用者栈上 add12and13
stack=2 / locals=0 静态调用不压 this add12and13Static
args_size=3 / locals=3 参数个数与 slot 数相等:三个值各占一个 slot addTwo
args_size=2 / locals=2 静态方法没有 this,两项都少 1 addTwoStatic
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;实例版调用者的 stack=4。三个 int 求和仍是两两上栈,stack 不会变成 3。描述符变成 (III)I,所以会出现一条新的 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 的单步演示
番外二 递归里有什么 多层帧、等待中的操作数栈、返回传播

参考资料

相关推荐
计算机毕设定制辅导-无忧学长11 分钟前
《基于SpringBoot的肩周炎健康管理系统设计与实现》
java·vue.js·spring boot·mysql·肩周炎健康管理系统
Java码农也是农43 分钟前
Rust、Java、Python、C++ 有什么区别?从 CPU 执行到内存管理
java·python·rust
特立独行的猫A10 小时前
DDS 调试助手:用仓颉写的跨厂商 DDS 抓包与监控工具(开源)
后端
码事漫谈11 小时前
OPC到底是什么:一年冒出1600万家,九成活不过2026年
后端
陆枫Larry11 小时前
从一个 Java Demo 聊聊 H2 数据库的前世今生
后端
特立独行的猫A11 小时前
仓颉版 Tauri 单文件 exe:gcc -r 一招破解 GCC-LTO 静态库链接
后端
金銀銅鐵11 小时前
带您看懂字节码指令(番外二):递归里有什么——三层 fact 帧怎么叠起来
java·jvm·后端
皮皮林55112 小时前
私活神器,腾讯低代码平台开源了,拖拽就能开发~
后端