关于Java字节码中局部变量表索引的问题

smallclover
  • 173

1.反编译一段java代码后,对其中一部分不理解。

源代码

public class HelloWorld {
    public static void main(String[] args) {
        short x = 10;
        double y = 20.25;
        double z = -x + y;
    }
}

反编译之后

  Last modified 2018-2-18; size 300 bytes
  MD5 checksum fab4b384ad0293dd52a63369a0010c17
  Compiled from "HelloWorld.java"
public class HelloWorld
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Methodref          #5.#14         // java/lang/Object."<init>":()V
   #2 = Double             20.25d
   #4 = Class              #15            // HelloWorld
   #5 = Class              #16            // java/lang/Object
   #6 = Utf8               <init>
   #7 = Utf8               ()V
   #8 = Utf8               Code
   #9 = Utf8               LineNumberTable
  #10 = Utf8               main
  #11 = Utf8               ([Ljava/lang/String;)V
  #12 = Utf8               SourceFile
  #13 = Utf8               HelloWorld.java
  #14 = NameAndType        #6:#7          // "<init>":()V
  #15 = Utf8               HelloWorld
  #16 = Utf8               java/lang/Object
{
  public HelloWorld();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: return
      LineNumberTable:
        line 1: 0

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=4, locals=6, args_size=1
         0: bipush        10
         2: istore_1
         3: ldc2_w        #2                  // double 20.25d
         6: dstore_2
         7: iload_1
         8: ineg
         9: i2d
        10: dload_2
        11: dadd
        12: dstore        4
        14: return
      LineNumberTable:
        line 3: 0
        line 4: 3
        line 5: 7
        line 6: 14
}
SourceFile: "HelloWorld.java"

这里要问的是

        12: dstore        4

这一段代码,这里的4是表示什么意思,我认为这个4应该是局部变量表的第四个位置,但是,在代码里只有三个数。而且,istore_1 表示1位置存储整数10,dstore_2表示存储浮点数20.25d,如果要在第三个位置存储计算的结果应该是dstore_3,不知为何这里是4。

回复
阅读 2.2k
1 个回答

locals=6,args(1个),short x(1个),double y(2个),double z(2个)
dstore 4意思是从栈顶弹出2个字的值,因为是d型的,并把结果赋给第5和第6个local位置。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏