开发者

How can "this" of the outer class be accessed from an inner class?

开发者 https://www.devze.com 2022-12-28 06:47 出处:网络
Is it possible to get a reference to this from within a Java inner class? i.e. class Outer { void aMethod() {

Is it possible to get a reference to this from within a Java inner class?

i.e.

class Outer {

  void aMethod() {

  开发者_运维百科  NewClass newClass = new NewClass() {
      void bMethod() {
        // How to I get access to "this" (pointing to outer) from here?
      }
    };
  }
}


You can access the instance of the outer class like this:

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.


Prepend the outer class's class name to this:

outer.this


yes you can using outer class name with this. outer.this


Extra: It is not possible when the inner class is declared 'static'.

0

精彩评论

暂无评论...
验证码 换一张
取 消