[英]In Java how can I reference an anonymous inner class from within itself?
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. 我没有做太多Java,所以我可能会在这里咆哮错误的树。 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! 感谢所有快速解答!
为什么不使用:
doStuffWith(this);
I may be wrong, but I think you want to replace doStuffWith(callback);
我可能错了,但我认为你想要替换doStuffWith(callback);
with doStuffWith(this);
用doStuffWith(this);
. 。
http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html
您必须使用关键字试过this
?
You could use this
instead of callback
您可以使用this
而不是callback
(just tried it, my compiler does complain about your way, but if you use this
it doesnt: (刚刚试了一下,我的编译器不抱怨的方式,但如果你使用this
它不:
final Runnable callback = new Runnable() {
public void run() {
if (something()) {
doStuffWith(this);
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.