变量应该是最终的内部监听器 [英] Variable should be final inside listener

查看:156
本文介绍了变量应该是最终的内部监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

不能引用在不同方法中定义的内部类中的非final变量
b $ b 为什么只能在匿名类中访问最终变量?

在SO和google中寻找这个问题的答案,但不能找不到。

Looked over in SO and google looking for an answer to this question but could not find any.

我有以下代码:

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();
   }
});

编译器返回:


从内部类中访问局部变量变量;需要
被宣布为最终

local variable variable is accessed from within inner class; needs to be declared final

为什么变量必须是最终的?

推荐答案

这是因为你使用的是匿名内部类。
会发生什么,编译器会为您创建类。它将其称为您的外部类,并添加 $ 和数字,例如 $ $ 2 等。

It is because you are using anonymous inner class. What happens is that compiler creates class for you. It calls it as your outer class and adds $ and number, e.g. $, $2 etc.

该类有参考外部类自动初始化,因此它的实例可以使用外部类的方法和字段。

The class has reference to outer class initialized automatically, so its instance can use methods and fields of outer class.

但你的课程是匿名的。它定义了内部方法,可以使用在此匿名类之前定义的内部变量。问题是它怎么能这样做?实际上,您无法参考运行方法的实例来访问其变量。答案是从匿名内部类引用的所有方法变量都被复制到匿名内部类。因此,变量必须是最终的:否则有人可以从外部类更改它们的值,并且更改将不会在内部类中可见。

But your class is anonymous. It kind of defined inside method and can use its internal variables defined before this anonymous class. The question is "how can it do it?" Really, you cannot refer to "instance of running method" to access its variables. The answer is that all method variables referenced from anonymous inner class are copied to the anonymous inner class . Therefore the variables are required to be final: otherwise somebody can change their values from the outer class and the changes will not be visible into the inner class.

这篇关于变量应该是最终的内部监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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