Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 903
Sami Samhuri Avatar asked Dec 05 '22 23:12

Sami Samhuri


1 Answers

Why not use:

doStuffWith(this);
like image 141
Bert F Avatar answered Dec 08 '22 04:12

Bert F