74

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

IE

class Outer {

  void aMethod() {

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

5 回答 5

103

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

Outer.this
于 2010-04-28T17:24:13.033 回答
34

外部.this

IE。

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

顺便说一句,在 Java 中,类名按约定以大写开头。

于 2010-04-28T17:36:03.660 回答
9

将外部类的类名添加到此:

outer.this
于 2010-04-28T17:24:37.550 回答
3

是的,您可以将外部类名与this一起使用。 外部.this

于 2010-04-28T17:28:02.403 回答
2

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

于 2018-10-22T18:39:46.080 回答