但是,如果变量是封闭类的成员字段,我发现匿名类仍然可以访问非最终变量:How can I access enclosing class instance variables from inside the anonymous class?
我很困惑.我们确保只能在匿名类中访问最终的局部变量,因为我们不希望变量应该在匿名类和本地函数之间失去同步.如果我们尝试在匿名类中访问非最终的封闭类成员,那么同样的原因应该适用于这种情况.
为什么不是一个问题?
解决方法
在封闭类的成员字段的情况下,没有副本.相反,匿名类获取对包围类的引用,从而访问外部类的任何/所有成员字段和方法.所以即使这个字段的值发生变化,这个变化也反映在匿名类中,因为它是相同的引用.
I am confused. We ensure that only a final local variable can be
accessed in anonymous class because we don’t want that the variable
should be out-of-sync between anonymous class and local function. The
same reason should apply to the case if we try to access a non-final
enclosing class member in anonymous class.
如你所见,情况并非如此.复制只适用于局部变量,而不是封闭类的成员字段.原因当然是一个匿名类保留对封闭类的隐含引用,通过该引用,它可以访问任何/所有成员字段&外部类的方法
引用以下链接:
A member variable exists during the lifetime of the enclosing object,so it can be referenced by the inner class instance. A local variable,however,exists only during the method invocation,and is handled differently by the compiler,in that an implicit copy of it is generated as the member of the inner class. Without declaring the local variable final,one could change it,leading to subtle errors due to the inner class still referring to the original value of that variable.
参考文献: