gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:00:38 25 4
gpt4 key购买 nike

我们知道在匿名类中只能访问 final 局部变量,这是有充分理由的:Why are only final variables accessible in anonymous class? .

但是,我发现如果变量是封闭类的成员字段,匿名类仍然可以访问非最终变量:How can I access enclosing class instance variables from inside the anonymous class?

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

为什么不用担心?

最佳答案

在局部变量的情况下,变量的副本 是匿名类实例接收的内容。因此,在匿名类中使用局部变量之前,必须将其设置为final,这样它的值以后就不会改变。

对于封闭类的成员字段,没有副本。相反,匿名类获取对封闭类的引用,从而访问外部类的任何/所有成员字段和方法。因此,即使字段的值发生变化,该变化也会反射(reflect)在匿名类中,因为它是相同引用。

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.

引用资料:

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? .

关于java - 为什么匿名类可以访问封闭类的非最终类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30773542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com