当地new int[]的处理

本地new int[]的处理

本文主要展示Java代码函数中定义的数组初始化的处理。为了简单起见,我们使用如下的代码:

    public static void main(String[] argv) {
        int[] arr = new int[]{1, 2, 3, 4};

        return;
    }

编译后的代码如下:

    Code:
      stack=4, locals=2, args_size=1
         0: iconst_4      
         1: newarray       int
         3: dup           
         4: iconst_0      
         5: iconst_1      
         6: iastore       
         7: dup           
         8: iconst_1      
         9: iconst_2      
        10: iastore       
        11: dup           
        12: iconst_2      
        13: iconst_3      
        14: iastore       
        15: dup           
        16: iconst_3      
        17: iconst_4      
        18: iastore       
        19: astore_1      
        20: return    

指令0-1初始化一个长度为4int数组。

当地new int[]的处理

指令3在操作栈中复制数组指针。

当地new int[]的处理

指令4-6则将数组的0号元素赋值1。同样的指令7-10,11-14,15-18分别给数组的1号,2号,3号元素赋值1,2,3

当地new int[]的处理

19指令把数组arr引用存到本地变量数组1slot

当地new int[]的处理

综上,本地数组初始化时编译器在一开始时就确定元素的个数。然后通过iastore进行赋值