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


70

是否可以this从Java内部类中获取对它的引用?

class Outer {

  void aMethod() {

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

Answers:



32

外层

即。

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

顺便说一句,在Java中,类名按照惯例以大写字母开头。



2

是的,您可以在使用外部类名。 外在


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.