简体   繁体   English

如何从内部类访问外部类的“ this”?

[英]How can “this” of the outer class be accessed from an inner class?

Is it possible to get a reference to this from within a Java inner class? 是否可以从Java内部类中this进行引用?

ie

class Outer {

  void aMethod() {

    NewClass newClass = new NewClass() {
      void bMethod() {
        // How to I get access to "this" (pointing to outer) from here?
      }
    };
  }
}

您可以这样访问外部类的实例:

Outer.this

Outer.this 外层

ie. 即。

class Outer {
    void aMethod() {
        NewClass newClass = new NewClass() {
            void bMethod() {
                System.out.println( Outer.this.getClass().getName() ); // print Outer
            }
        };
    }
}

BTW In Java class names start with uppercase by convention. 顺便说一句,在Java中,类名按照惯例以大写开头。

在外部类的类名之前添加以下内容:

outer.this

yes you can using outer class name with this . 是的,您可以在使用外部类名。 outer.this 外在

附加:内部类被声明为“静态”时,这是不可能的。

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

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