Setting outer variable from anonymous inner class

后端 未结 9 847
臣服心动
臣服心动 2020-11-28 07:03

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         


        
9条回答
  •  难免孤独
    2020-11-28 08:04

    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];
    

提交回复
热议问题