匿名内部类中的 Java 局部变量可见性 - 为什么需要“final"关键字? [英] Java local variable visibility in anonymous inner classes - why is 'final' keyword required?

查看:19
本文介绍了匿名内部类中的 Java 局部变量可见性 - 为什么需要“final"关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么我不能总是从侦听器"或处理程序"内部访问变量.

I don't understand why I cannot always access a variable from inside a 'listener' or 'handler'.

这是我的代码:

Button btnDownload = new Button(myparent, SWT.NONE);
btnDownload.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                btnDownload.setEnabled(false); // I CAN'T 
            }
        });

唯一的方法是使用 final 关键字声明它:

The only way is to declare it using the final keyword:

final Button btnDownload = new Button(myparent, SWT.NONE);

为什么我需要声明一个变量 final 才能在事件中访问?

Why do I need to declare a variable final to gain access inside an event?

推荐答案

你的 SelectionAdapter 是一个匿名内部类,我认为这很清楚:

Your SelectionAdapter is an anonymous inner class and I think this makes it clear:

本地类绝对可以引用实例变量.它们不能引用非 final 局部变量的原因是因为局部类实例可以在方法返回后保留在内存中.当方法返回时,局部变量超出范围,因此需要它们的副本.如果变量不是 final 则方法中变量的副本可能会发生变化,而本地类中的副本则不会,因此它们会不同步.

Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren’t final then the copy of the variable in the method could change, while the copy in the local class didn’t, so they’d be out of synch.

匿名内部类需要最终变量,因为它们在 Java 中的实现方式.匿名内部类 (AIC) 通过创建一个私有实例字段来使用局部变量,该字段包含局部变量值的副本.内部类实际上并没有使用局部变量,而是一个副本.在这一点上,如果原始值或复制的值发生变化,就会发生坏事"™,这应该是相当明显的;会有一些意想不到的数据同步问题.为了防止此类问题,Java 要求您将 AIC 将使用的局部变量标记为 final(即不可更改).这保证了内部类的局部变量副本将始终与实际值匹配.

Anonymous inner classes require final variables because of the way they are implemented in Java. An anonymous inner class (AIC) uses local variables by creating a private instance field which holds a copy of the value of the local variable. The inner class isn’t actually using the local variable, but a copy. It should be fairly obvious at this point that a "Bad Thing"™ can happen if either the original value or the copied value changes; there will be some unexpected data synchronization problems. In order to prevent this kind of problem, Java requires you to mark local variables that will be used by the AIC as final (i.e., unchangeable). This guarantees that the inner class’ copies of local variables will always match the actual values.

这篇关于匿名内部类中的 Java 局部变量可见性 - 为什么需要“final"关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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