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

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

问题描述:

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

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?

我刚刚发现这个。使用 OuterClassName.this

I just found this recently. Use OuterClassName.this.

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

更新如果你只是想要对象本身(而不是调用成员),然后 Outer.this 就可以了。

Updated If you just want the object itself (instead of invoking members), then Outer.this is the way to go.