在Java中,如何从其内部引用匿名内部类?

发布于 2024-10-13 17:37:03 字数 586 浏览 11 评论 0原文

我正在定义一个回调,并希望从其内部引用回调。编译器不喜欢这样,并声称引用回调的变量未初始化。代码如下:

final Runnable callback = new Runnable() {
    public void run() {
        if (someCondition()) {
            doStuffWith(callback); // <<--- compiler says "the local variable callback may not be initialized"
        }
    }
};
// Here callback is defined, and is certainly defined later after I actually do something with callback!

显然,编译器错误地认为,当我们到达定义内部方法回调时。我如何告诉编译器这段代码很好,或者如何以不同的方式编写它来安抚编译器?我没有做过太多 Java 工作,所以我可能在这里找错了对象。还有其他惯用的方法吗?对我来说,这似乎是一个非常简单的构造。

编辑:当然,这、那太容易了。感谢您的快速解答!

I'm defining a callback and would like to refer to the callback from within itself. The compiler does not like this and claims that the variable referring to the callback is not initialized. Here's the code:

final Runnable callback = new Runnable() {
    public void run() {
        if (someCondition()) {
            doStuffWith(callback); // <<--- compiler says "the local variable callback may not be initialized"
        }
    }
};
// Here callback is defined, and is certainly defined later after I actually do something with callback!

Clearly the compiler is mistaken as by the time we reach the inner method callback is defined. How do I tell the compiler that this code is fine, or how can I write it differently to placate the compiler? I haven't done much Java so I could be barking up the wrong tree here. Is there some other idiomatic way to do this? It seems like a pretty simple construct to me.

edit: Of course, this, that was too easy. Thanks for all the quick answers!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

从此见与不见 2024-10-20 17:37:03

为什么不使用:

doStuffWith(this);

Why not use:

doStuffWith(this);
七堇年 2024-10-20 17:37:03

我可能是错的,但我认为你想用 doStuffWith(this); 替换 doStuffWith(callback);

http://download.oracle.com/javase/tutorial/java/javaOO /thiskey.html

I may be wrong, but I think you want to replace doStuffWith(callback); with doStuffWith(this);.

http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html

刘备忘录 2024-10-20 17:37:03

您是否尝试过使用关键字 this

Have you tried using the keyword this?

酒解孤独 2024-10-20 17:37:03

您可以使用 this 而不是 callback

(刚刚尝试过,我的编译器确实抱怨您的方式,但如果您使用 this 它不会:

final Runnable callback = new Runnable() {
    public void run() {
        if (something()) {
            doStuffWith(this);
        }
    }
};

You could use this instead of callback

(just tried it, my compiler does complain about your way, but if you use this it doesnt:

final Runnable callback = new Runnable() {
    public void run() {
        if (something()) {
            doStuffWith(this);
        }
    }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文