问题描述
将局部变量声明为final以便从匿名类访问它们的规则背后的原因是什么?
What is the reason behind the rule of having local variables declared as final in order to access them from anonymous class?
推荐答案
当您从匿名类访问 final
变量时,编译器会秘密地将其值复制到匿名类的成员变量中.例如:
When you access a final
variable from an anonymous class, the compiler secretly copies their value into a member variable of the anonymous class. eg:
Runnable foo() {
final int x = 42;
return new Runnable() {
void run() {
System.out.writeln(x);
}
};
}
成为:
// the actual name is generally illegal in normal java syntax
class internal_Runnable implements Runnable {
final int x;
internal_Runnable(int _x) { x = _x; }
void run() {
System.out.writeln(x);
}
}
void foo() {
final x = 42;
return new internal_Runnable(x);
}
如果该变量不是最终变量并且允许更改,则匿名类实例中缓存的值可能不同步.通过使用闭包可以避免这种情况,闭包是一个对象,该对象保存所有局部变量的值,原始函数和新的匿名类实例都可以访问.例如, .NET使用闭包.但是,这可能会导致性能下降,并且也许由于这个原因,Java语言设计人员决定不支持完全闭包.
If the variable were not final and were allowed to change, the value cached in the anonymous class instance could go out of sync. This could have been avoided by use of a closure - that is, an object holding the values of all local variables, that both the original function and the new anonymous class instance access. .NET uses closures, for example. However, this can incur a performance hit, and perhaps for that reason, the Java language designers decided not to support full closures.
这篇关于为什么我的局部变量应该是最终的,以便可以从匿名类访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!