Where is stored captured variable in Java? -
i'm trying understand concept of captured variable in java.
i found quite detailed article it: http://www.devcodenote.com/2015/04/variable-capture-in-java.html
and i'm not sure bytecode part:
similarly, accessing local variables of enclosing method, hidden copy of variable made , kept in inner class file accesses variable.
how can saved class file (during compilation), when final primitive values may 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 wrong, local variables copied localclass's space in method area in runtime?
the author seems referring fact captured variables translated fields of local/anonymous class.
if disasemble localclass
can see (where main
name of 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 local variable y
, , second field reference enclosing instance. furthermore, these values passed constructor of local class implicitly.
essentially localclass
looks 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 } }
Comments
Post a Comment