Where is stored captured variable in Java?

…衆ロ難τιáo~ 提交于 2019-12-20 04:15:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!