这是各种单个字节码操作如何获取其输入以及它们如何提供其输出的方式。
例如,考虑
iadd将两个
ints相加的运算。要使用它,您将两个值压入堆栈,然后使用它:
iload_0 # Push the value from local variable 0 onto the stackiload_1 # Push the value from local variable 1 onto the stackiadd # Pops those off the stack, adds them, and pushes the result
现在,堆栈上的最高值是这两个局部变量的总和。下一个操作可能会使用该顶部堆栈的值并将其存储在某个位置,或者我们可能会将另一个值压入堆栈以执行其他操作。
假设您要将三个值加在一起。堆栈使操作变得简单:
iload_0 # Push the value from local variable 0 onto the stackiload_1 # Push the value from local variable 1 onto the stackiadd # Pops those off the stack, adds them, and pushes the resultiload_2 # Push the value from local variable 2 onto the stackiadd # Pops those off the stack, adds them, and pushes the result
现在,堆栈上的最高值是将这三个局部变量相加的结果。
让我们更详细地看第二个例子:
我们假设:
- 开始时栈是空的 (实际上几乎从来都不是真的,但是在开始之前我们并不关心 栈中的内容 )
- 局部变量0包含
27
- 局部变量1包含
10
- 局部变量2包含
5
所以最初:
+------+| 堆叠+------++------+
那我们做
iload_0 # Push the value from local variable 0 onto the stack
现在我们有
+------+| 堆叠+------+| 27 |+------+
下一个
iload_1 # Push the value from local variable 1 onto the stack+------+| 堆叠+------+| 10 || 27 |+------+
现在我们进行添加:
iadd # Pops those off the stack, adds them, and pushes the result
它“弹出”
10和
27离开堆栈,将它们加在一起,然后推入结果(
37)。现在我们有:
+------+| 堆叠+------+| 37 |+------+
第三次时间
int:
iload_2 # Push the value from local variable 2 onto the stack+------+| 堆叠+------+| 5 || 37 |+------+
我们做第二件事
iadd:
iadd # Pops those off the stack, adds them, and pushes the result
这给了我们:
+------+| 堆叠+------+| 42 |+------+
(当然,这是
对宇宙和一切生命的终极问题的解答。)



