为什么我的局部变量应该是最终的,以便可以从匿名类访问? [英] Why should my local variables be final to be accessible from anonymous class?

查看:51
本文介绍了为什么我的局部变量应该是最终的,以便可以从匿名类访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
无法引用到使用不同方法定义的内部类中的非最终变量

将局部变量声明为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.

这篇关于为什么我的局部变量应该是最终的,以便可以从匿名类访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆