Is there any way to access caller-scoped variables from an anonymous inner class in Java?
Here\'s the sample code to understand what I need:
public L
Anonymous classes/methods are not closures - this is exactly the difference.
The problem is that doWork()
could create a new thread to call execute()
and getNumber()
could return before the result is set - and even more problematically: where should execute()
write the result when the stack frame that contains the variable is gone? Languages with closures have to introduce a mechanism to keep such variables alive outside their original scope (or ensure that the closure is not executed in a separate thread).
A workaround:
Long[] result = new Long[1];
...
result[0] = st.getLong(4) ;
...
return result[0];