java – 为什么匿名类访问封闭类的非最终类成员

前端之家收集整理的这篇文章主要介绍了java – 为什么匿名类访问封闭类的非最终类成员前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们知道只能在匿名类中访问最终的局部变量,这里有一个很好的理由: Why are only final variables accessible in anonymous class?.

但是,如果变量是封闭类的成员字段,我发现匿名类仍然可以访问非最终变量: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.

参考文献:

Why a non-final “local” variable cannot be used inside an inner class,and instead a non-final field of the enclosing class can?.

原文链接:https://www.f2er.com/java/125700.html

猜你在找的Java相关文章