简体   繁体   English

java如何从内部内部类实现对封闭类的访问?

[英]How java implement the access to the enclosing class from an inner inner class?

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 . 我一直感到惊讶的Java允许InnerInnerClass到直接访问EnclosingClass How is this code implemented internally by Java? 这个代码是如何在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 ? InnerInnerClass保持两个指针(一个在InnerClass和其他的EnclosingClass )或InnerInnerClass访问EnclosingClass通过InnerClass

You just need to disassemble the resulting class with javap to see what's going on: 您只需要使用javap反汇编生成的类,看看发生了什么:

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. public和private是一个指针问题,它是一个编译器问题。

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. 因为私有方法getEnclosing()属于InnerClass的范围,所以可以在整个类中访问它。

Note that pointers have nothing to do with the issue. 请注意,指针与问题无关。
Using reflection you can still access private members of a class. 使用反射,您仍然可以访问类的私有成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM