I have created an inner class in an inner class :
public class EnclosingClass {
public class InnerClass {
private EnclosingClass getEnclosing() {
return EnclosingClass.this;
}
public class InnerInnerClass {
private InnerClass getEnclosing() {
return InnerClass.this;
}
private EnclosingClass getEnclosingOfEnclosing() {
return EnclosingClass.this;
}
}
}
}
I have been surprised that java allows the InnerInnerClass
to access directly the EnclosingClass
. How is this code implemented internally by Java?
The InnerInnerClass
keeps two pointers (one on the InnerClass
and the other on the EnclosingClass
) or the InnerInnerClass access the EnclosingClass
through the InnerClass
?
You just need to disassemble the resulting class with javap to see what's going on:
private EnclosingClass getEnclosingOfEnclosing();
Code:
0: aload_0
1: getfield #1 // Field this$1:LEnclosingClass$InnerClass;
4: getfield #3 // Field EnclosingClass$InnerClass.this$0:LEnclosingClass;
7: areturn
So first it gets the instance of the directly enclosing class, then it gets the "top-level" enclosing class from that.
如果内部类不是“静态”,则它们在包含它们的类的内部包含引用。
除非你使内部类是静态的,否则它确实引用了它所存在的实例,并且可以引用它的成员(包括private),内部内部类,内部内部内部类等也是如此。
public and private is a pointer issue, it's a compiler issue.
The question is one of the compiler enforcing the scope of a class/variable/method. Because the private method getEnclosing()
falls with the the scope of InnerClass
, it can be accessed throughout that class.
Note that pointers have nothing to do with the issue.
Using reflection you can still access private members of a class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.