(我的意思是它们在字节码中的代表相同)
让我们来了解一下。拿这个代码
class Example {
private static int[] outside = new int[]{1};
public static void main(String [] args){
final int[] inside = new int[]{2};
Object inner = new Object(){{
System.out.println(outside[0]);
System.out.println(inside[0]);
}};
}
}
编译它以获得两个类,然后将它们反汇编javap -c
以获取
class Example {
Example();
Code:
0: aload_0
1: invokespecial #2 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: newarray int
3: dup
4: iconst_0
5: iconst_2
6: iastore
7: astore_1
8: new #3 // class Example$1
11: dup
12: aload_1
13: invokespecial #4 // Method Example$1."<init>":([I)V
16: astore_2
17: return
static int[] access$000();
Code:
0: getstatic #1 // Field outside:[I
3: areturn
static {};
Code:
0: iconst_1
1: newarray int
3: dup
4: iconst_0
5: iconst_1
6: iastore
7: putstatic #1 // Field outside:[I
10: return
}
和
final class Example$1 {
final int[] val$inside;
Example$1(int[]);
Code:
0: aload_0
1: aload_1
2: putfield #1 // Field val$inside:[I
5: aload_0
6: invokespecial #2 // Method java/lang/Object."<init>":()V
9: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
12: invokestatic #4 // Method Example.access$000:()[I
15: iconst_0
16: iaload
17: invokevirtual #5 // Method java/io/PrintStream.println:(I)V
20: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
23: aload_0
24: getfield #1 // Field val$inside:[I
27: iconst_0
28: iaload
29: invokevirtual #5 // Method java/io/PrintStream.println:(I)V
32: return
}
我们看到该变量inside
是作为类中的一个字段创建的,而Example$1
该变量outside
是通过. 因此不 - 它们在字节码中的表示不同。access$000
Example