是的,这是真的.至少对于Sun javac来说.看看下面的例子:
public class OuterClass {
public static void main(String... args) {
InnerClass.foo = 7;
System.out.println(InnerClass.foo);
}
private static class InnerClass {
private static int foo;
private static int bar;
}
}
$javap -c OuterClass\$InnerClass
Compiled from "OuterClass.java"
class OuterClass$InnerClass extends java.lang.Object{
static int access$002(int);
Code:
0: iload_0
1: dup
2: putstatic #1; //Field foo:I
5: ireturn
static int access$000();
Code:
0: getstatic #1; //Field foo:I
3: ireturn
}
它定义了一个静态int访问$002(int)来设置值,静态int访问$000()来获取值. setter也返回值,大概是为了轻松编译someVariable = InnerClass.foo = 5.
$javap -c OuterClass
Compiled from "OuterClass.java"
public class OuterClass extends java.lang.Object{
public OuterClass();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return
public static void main(java.lang.String[]);
Code:
0: bipush 7
2: invokestatic #2; //Method OuterClass$InnerClass.access$002:(I)I
5: pop
6: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
9: invokestatic #4; //Method OuterClass$InnerClass.access$000:()I
12: invokevirtual #5; //Method java/io/PrintStream.println:(I)V
15: return
}
在第2行和第9行,它分别调用setter(访问$002)和getter(访问$000).
另请注意,只有在需要时才会引入这些访问者方法.例如,bar字段从未从类外部访问,因此编译器仅为foo字段生成getter / setter.