method local innerclasses accessing the local variables of the method

前端 未结 2 1633
-上瘾入骨i
-上瘾入骨i 2020-12-16 08:37

Hi I was going through the SCJP book about the innerclasses, and found this statement, it goes something like this.

A method local class can only refe

相关标签:
2条回答
  • 2020-12-16 09:22

    The reason is, when the method local class instance is created, all the method local variables it refers to are actually copied into it by the compiler. That is why only final variables can be accessed. A final variable or reference is immutable, so it stays in sync with its copy within the method local object. Were it not so, the original value / reference could be changed after the creation of the method local class, giving way to confusing behaviour and subtle bugs.

    Consider this example from the JavaSpecialist newsletter no. 25:

    public class Access1 {
      public void f() {
        final int i = 3;
        Runnable runnable = new Runnable() {
        public void run() {
          System.out.println(i);
        }
        };
      }
    }
    

    The compiler turns the inner class into this:

    class Access1$1 implements Runnable {
      Access1$1(Access1 access1) {
        this$0 = access1;
      }
      public void run() {
        System.out.println(3);
      }
      private final Access1 this$0;
    }
    

    Since the value of i is final, the compiler can "inline" it into the inner class.

    0 讨论(0)
  • 2020-12-16 09:28

    As I see it, accessing local variables from method-local-classes (e.g. anonymous class) is a risky thing. It is allowed by the compiler, but it requires good understanding of what is going on.

    When the inner class is instantiated, all the references to local variables it uses are copied, and passed as implicit constructor parameters (check the bytecode). Actually the compiler could have allowed making the references non-final, but it would be confusing, since it would not be clear what happens if the method alters the references after the instantiation.

    However, making the reference final does not eliminate all problems. While the reference is immutable, the object behind the reference may still be mutable. Any mutations of the object done between the instantiation of the inner class until its activation will be seen by the inner class, and sometimes this is not the intention of the programmer.

    0 讨论(0)
提交回复
热议问题