What are captured variables in Java Local Classes

前端 未结 3 961
慢半拍i
慢半拍i 2020-12-05 11:32

The Java documentation for Local Classes says that:

In addition, a local class has access to local variables. However, a local class can only access

相关标签:
3条回答
  • 2020-12-05 11:33

    Here is a post describing it: http://www.devcodenote.com/2015/04/variable-capture-in-java.html

    Here is a snippet from the post:

    ”It is imposed as a mandate by Java that if an inner class defined within a method references a local variable of that method, that local variable should be defined as final.”

    This is because the function may complete execution and get removed from the process stack, with all the variables destroyed but it may be the case that objects of the inner class are still on the heap referencing a particular local variable of that function. To counter this, Java makes a copy of the local variable and gives that as a reference to the inner class. To maintain consistency between the 2 copies, the local variable is mandated to be “final” and non-modifiable.

    0 讨论(0)
  • 2020-12-05 11:56

    What is captured variable,what is its use and why is that needed?

    A captured variable is one that has been copied so it can be used in a nested class. The reason it has to be copied is the object may out live the current context. It has to be final (or effectively final in Java 8) so there is no confusion about whether changes to the variable will be seen (because they won't)

    Note: Groovy does have this rule and a change to the local variable can mean a change to the value in the enclosing class which is especially confusing if multiple threads are involved.

    An example of capture variable.

    public void writeToDataBase(final Object toWrite) {
        executor.submit(new Runnable() {
            public void run() {
                 writeToDBNow(toWrite);
            }
        });
        // if toWrite were mutable and you changed it now, what would happen !?
    }
    // after the method returns toWrite no longer exists for the this thread...
    
    0 讨论(0)
  • 2020-12-05 11:56

    A captured variable is one from the outside of your local class - one declared in the surrounding block. In some languages this is called a closure.

    In the example from the Oracle Docs (simplified) the variable numberLength, declared outside of class PhoneNumber, is "captured".

    final int numberLength = 10;  // in JDK7 and earlier must be final...
    
    class PhoneNumber {
       // you can refer to numberLength here...  it has been "captured"
    }
    
    0 讨论(0)
提交回复
热议问题