本文介绍了为什么匿名类可以访问封闭类的非最终类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道在匿名类中只能访问最终的局部变量,并且在这里有充分的理由:。



但是,我发现一个匿名类如果变量是封闭类的成员字段,则仍可以访问非最终变量:



我很困惑。我们确保匿名类中只能访问最终的局部变量,因为我们不希望该变量在匿名类和本地函数之间不同步。如果我们尝试访问匿名类中的非最终封闭类成员,则同样的原因也适用于这种情况。



为什么不用担心?

解决方案

对于局部变量,匿名类就是变量的副本实例接收。因此,必须先将本地变量设置为 final ,然后才能在匿名类中使用它,以便其值以后不会更改。



对于封闭类的成员字段, 没有副本 。而是,匿名类获取对封闭类的引用,从而可以访问外部类的任何/所有成员字段和方法。因此,即使该字段的值发生变化,该更改也将反映在匿名类中,因为它是 same 引用。

并非如此。复制仅发生在局部变量上,而不发生在封闭类的成员字段上。 当然,原因是匿名类拥有对封闭类的隐式引用,并且通过该引用,它可以访问任何/所有成员字段&



引用以下链接:

参考文献:



1。 。 / p>

We know that only final local variables can be accessed in an anonymous class, and there is a good reason here: Why are only final variables accessible in anonymous class?.

However, I found that an anonymous class can still access a non-final variable if the variable is an member field of the enclosing 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.

Why would it not be a concern?

解决方案

In the case of a local variable, a copy of the variable is what the anonymous class instance receives. For this reason, the local variable has to be made final before it can be used within the anonymous class, so that its value may not change later.

In the case of a member field of the enclosing class, there is no copy. Rather, the anonymous class gets a reference to the enclosing class, and thereby it accesses any/all member fields and methods of the outer class. So even if the value of the field changes, the change is reflected in the anonymous class as well, because it is the same reference.

As you see, that is not the case. The copying happens only for local variables, not for member fields of the enclosing class. The reason is, of course, that an anonymous class holds an implicit reference to the enclosing class, and through that reference it can access any/all member fields & methods of the outer class.

To quote the link below:

References:

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

这篇关于为什么匿名类可以访问封闭类的非最终类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:56