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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2731719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:14:22  来源:igfitidea点击:

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

javainner-classes

提问by llm

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

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

i.e.

IE

class Outer {

  void aMethod() {

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

采纳答案by Guillaume

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

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

Outer.this

回答by staticman

Prepend the outer class's class name to this:

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

outer.this

回答by giri

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

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

回答by OscarRyz

Outer.this

外部.this

ie.

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 中,类名按照约定以大写开头。

回答by Josbert Lonnee

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

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