Java 来自匿名内部类的外部类的关键字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/56974/
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-11 07:44:47  来源:igfitidea点击:

Keyword for the outer class from an anonymous inner class

javaanonymous-inner-class

提问by shsteimer

In the following snippet:

在以下代码段中:

public class a {
    public void otherMethod(){}
    public void doStuff(String str, InnerClass b){}
    public void method(a){
        doStuff("asd",
            new InnerClass(){
                public void innerMethod(){
                    otherMethod();
                }
            }
        );
    }
}

Is there a keyword to refer to the outer class from the inner class? Basically what I want to do is outer.otherMethod(), or something of the like, but can't seem to find anything.

是否有关键字从内部类引用外部类?基本上我想做的是outer.otherMethod(),或类似的东西,但似乎找不到任何东西。

采纳答案by Bill the Lizard

In general you use OuterClassName.thisto refer to the enclosing instance of the outer class.

通常,您OuterClassName.this用来引用外部类的封闭实例。

In your example that would be a.this.otherMethod()

在你的例子中,这将是 a.this.otherMethod()

回答by jjnguy

OuterClassName.this.outerClassMethod();