在Java中,如何从其内部引用匿名内部类?
我正在定义一个回调,并希望从其内部引用回调。编译器不喜欢这样,并声称引用回调的变量未初始化。代码如下:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不使用:
Why not use:
我可能是错的,但我认为你想用
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);
withdoStuffWith(this);
.http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html
您是否尝试过使用关键字
this
?Have you tried using the keyword
this
?您可以使用
this
而不是callback
(刚刚尝试过,我的编译器确实抱怨您的方式,但如果您使用
this
它不会:You could use
this
instead ofcallback
(just tried it, my compiler does complain about your way, but if you use
this
it doesnt: