如何从 Java 中的匿名内部类获取对封闭类的引用?

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

How do you get a reference to the enclosing class from an anonymous inner class in Java?

javaoop

提问by Bill the Lizard

I'm currently creating an explicit reference to this in the outer class so that I have a name to refer to in the anonymous inner class. Is there a better way to do this?

我目前正在外部类中创建对 this 的显式引用,以便我在匿名内部类中有一个可以引用的名称。有一个更好的方法吗?

回答by Frank Krueger

I just found this recently. Use OuterClassName.this.

我最近才发现这个。使用OuterClassName.this.

class Outer {
    void foo() {
        new Thread() {
            public void run() {
                Outer.this.bar();
            }
        }.start();
    }
    void bar() {
        System.out.println("BAR!");
    }
}

UpdatedIf you just want the object itself (instead of invoking members), then Outer.thisis the way to go.

更新如果您只想要对象本身(而不是调用成员),那么Outer.this就是要走的路。

回答by John Topley

Use EnclosingClass.this

利用 EnclosingClass.this

回答by Scott Stanchfield

You can still use Outer.class to get the class of the outer class object (which will return the same Class object as Outer.this.getClass() but is more efficient)

您仍然可以使用 Outer.class 来获取外部类对象的类(它将返回与 Outer.this.getClass() 相同的 Class 对象,但效率更高)

If you want to access statics in the enclosing class, you can use Outer.name where name is the static field or method.

如果要访问封闭类中的静态数据,可以使用 Outer.name,其中 name 是静态字段或方法。