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

77

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

例如:

class Outer {

  void aMethod() {

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

110

您可以通过以下方式访问外部类的实例:

Outer.this

35

Outer.this

即:

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

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


10

在这个前面加上外部类的类名:

outer.this

3

是的,你可以使用外部类名和this关键字。 outer.this


1

额外说明:当内部类被声明为“静态”时,就不可能实现该功能。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接