【发布时间】:2012-06-10 15:08:29
【问题描述】:
可能重复:
Cannot refer to a non-final variable inside an inner class defined in a different method
Why are only final variables accessible in anonymous class?
在 SO 和谷歌中寻找这个问题的答案,但找不到任何答案。
我有以下代码:
MyClass variable = new MyClass();
Button b = new Button();
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println("You clicked the button");
variable.doSomething();
}
});
编译器返回这个:
局部变量变量是从内部类中访问的;需要 被宣布为最终的
variable 必须是 final 的技术原因是什么?
【问题讨论】:
-
感谢您的链接。没有解释为什么编译器是这样设计的。为什么内部类不引用外类并在需要时访问变量,而不是在第一次实例化时引用?
-
@GETah:如果变量是一个成员,那你就说得通了。但它是本地的。您不能依赖它定义的堆栈帧仍然存在,并且在 Java 中没有对变量的引用这样的东西。所以如果你想使用它,你几乎必须复制一份。
标签: java