为什么以下代码转换为java字节码中的新+ dup op指令? [英] Why does the following code translate to a new + dup op instructions in java bytecode?

查看:188
本文介绍了为什么以下代码转换为java字节码中的新+ dup op指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个分数类:

class Fraction {
    ...

    /** Invert current fraction */
    public Fraction inverse() {
        return new Fraction(den,num);
    }

    ...
}

这就是上述方法的字节码结果如下:

And this is what the bytecode of the above method turns out to be:

 0 new #1 <xyzTestes/system/fraction/Fraction>
 3 dup
 4 aload_0
 5 getfield #16 <xyzTestes/system/fraction/Fraction.den>
 8 aload_0
 9 getfield #14 <xyzTestes/system/fraction/Fraction.num>
12 invokespecial #27 <xyzTestes/system/fraction/Fraction.<init>>
15 areturn

我试图理解为什么将第3位的指令放在那里第一名。我要说我们只需要做以下工作就可以了:

I'm trying to understand why instruction at position 3 was put there in the first place. I'd say we'd only need to do the following to make it work:

 new #1 <xyzTestes/system/fraction/Fraction>
 aload_0
 getfield #16 <xyzTestes/system/fraction/Fraction.den>
 aload_0
 getfield #14 <xyzTestes/system/fraction/Fraction.num>
 invokespecial #27 <xyzTestes/system/fraction/Fraction.<init>>
 areturn

为什么不是这样?

推荐答案

当构造函数的字节码启动时,没有Fraction对象。 new 指令从堆中分配 Fraction 对象(未初始化),并在堆栈上留下对它的引用。 dup 指令是这样的,一个引用可用于调用< init> ,第二个用于<最后code> areturn 。

When the bytecode for the constructor starts, there is no Fraction object. The new instruction allocates a Fraction object (uninitialized) from the heap and leaves a reference to it on the stack. The dup instruction is so that one reference can be used to call <init> and the second used for the areturn at the end.

这篇关于为什么以下代码转换为java字节码中的新+ dup op指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆