如何从Java中的匿名内部类中获取对封闭类的引用? [英] How do you get a reference to the enclosing class from an anonymous inner class in Java?

查看:113
本文介绍了如何从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.

这篇关于如何从Java中的匿名内部类中获取对封闭类的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆