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

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

问题描述

我不明白为什么我不能总是从'listener'或'handler'中访问变量。

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 keyword:

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,那么方法中变量的副本可能会改变,而本地类中的副本则没有,所以它们会不同步。

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)通过创建私有实例字段来使用局部变量,该字段包含局部变量值的副本。内部类实际上并不使用局部变量,而是使用副本。在这一点上应该相当明显,如果原始值或复制值发生变化,可能会发生Bad Thing™;会有一些意外的数据同步问题。为了防止出现这种问题,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天全站免登陆