In Java, how can I refer to an anonymous inner class from within myself?

I am defining a callback and would like to reference the callback internally. The compiler does not like this and claims that the variable related to the callback is not initialized. Here is 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! 

Obviously, the compiler is wrong, since by the time the internal method callback has been reached. How do I tell the compiler that this code is fine, or how can I write it differently to calm the compiler? I haven’t done a lot of Java, so I could bark the wrong tree. Is there any other idiomatic way to do this? It seems to me that this is a fairly simple design.

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

+4
source share
4 answers

Why not use:

 doStuffWith(this); 
+10
source

Maybe I'm wrong, but I think you want to replace doStuffWith(callback); on doStuffWith(this); .

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

+3
source

Have you tried using the this ?

+1
source

You can use this instead of callback

(just tried, my compiler complains about your path, but if you use this , it does not:

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

Source: https://habr.com/ru/post/1336842/


All Articles