简体   繁体   中英

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. 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); with doStuffWith(this); .

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

您必须使用关键字试过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);
        }
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM