问题
I'm trying to understand concept of captured variable in Java.
I found quite detailed article about it: http://www.devcodenote.com/2015/04/variable-capture-in-java.html
and I'm not sure about bytecode part:
Similarly, for accessing local variables of an enclosing method, a hidden copy of the variable is made and kept in the inner class file from where it accesses the variable.
How can it be saved into class file (during compilation), when final primitive values may be not known in compile time?
for example:
void foo(int x){
final int y = 10 + x;
class LocalClass(){
LocalClass(){
System.out.println(y); // works fine
}
}
}
If author is wrong, are local variables copied into LocalClass's space in Method Area in runtime?
回答1:
The author seems to be referring to the fact that captured variables are translated into fields of a local/anonymous class.
If you disasemble LocalClass
you can see this (where Main
is the name of the enclosing class):
class Main$1LocalClass {
final int val$y;
final Main this$0;
Main$1LocalClass();
Code:
0: aload_0
1: aload_1
2: putfield #1 // Field this$0:LMain;
5: aload_0
6: iload_2
7: putfield #2 // Field val$y:I
10: aload_0
11: invokespecial #3 // Method java/lang/Object."<init>":()V
14: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream;
17: aload_0
18: getfield #2 // Field val$y:I
21: invokevirtual #5 // Method java/io/PrintStream.println:(I)V
24: return
}
The first field is the local variable y
, and the second field is a reference to the enclosing instance. Furthermore, these values are passed into the constructor of the local class implicitly.
Essentially LocalClass
looks like this:
class LocalClass {
final int val$y;
final Main this$0;
LocalClass(Main arg1, int arg2) {
this.this$0 = arg1; // bytecode 1-2
this.val$y = arg2; // bytecode 5-7
super(); // bytecode 10-11
System.out.println(this.val$y); // bytecode 14-21
}
}
来源:https://stackoverflow.com/questions/43414316/where-is-stored-captured-variable-in-java