方法本地内部类访问方法的局部变量 [英] method local innerclasses accessing the local variables of the method

查看:106
本文介绍了方法本地内部类访问方法的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在浏览关于内部类的SCJP书,发现这句话,它就是这样的。

Hi I was going through the SCJP book about the innerclasses, and found this statement, it goes something like this.


一种方法本地类只能引用标记为 final

的局部变量在解释中,指定的原因是关于本地类对象的范围和生命周期以及堆上的局部变量,但我无法理解。我在这里遗漏了关于 final 的所有内容吗?

and in the explanation the reason specified is about the scope and lifetime of the local class object and the local variables on the heap, but I am unable to understand that. Am I missing anything here about final??

推荐答案

原因是,当创建方法本地类实例时,它引用的所有方法局部变量实际上都被复制到它由编译器。这就是为什么只能访问 final 变量的原因。 final 变量或引用是不可变的,因此它与方法本地对象中的副本保持同步。如果不是这样,原始值/引用可以在创建方法本地类之后更改,让位于令人困惑的行为和微妙的错误。

The reason is, when the method local class instance is created, all the method local variables it refers to are actually copied into it by the compiler. That is why only final variables can be accessed. A final variable or reference is immutable, so it stays in sync with its copy within the method local object. Were it not so, the original value / reference could be changed after the creation of the method local class, giving way to confusing behaviour and subtle bugs.

考虑这个例子来自 JavaSpecialist newsletter no。 25

public class Access1 {
  public void f() {
    final int i = 3;
    Runnable runnable = new Runnable() {
    public void run() {
      System.out.println(i);
    }
    };
  }
}

编译器将内部类转换为:

The compiler turns the inner class into this:

class Access1$1 implements Runnable {
  Access1$1(Access1 access1) {
    this$0 = access1;
  }
  public void run() {
    System.out.println(3);
  }
  private final Access1 this$0;
}




因为 i 是最终的,编译器可以将它内联到内部类中。

Since the value of i is final, the compiler can "inline" it into the inner class.

这篇关于方法本地内部类访问方法的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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