Java Local Classes中捕获的变量是什么 [英] What are captured variables in Java Local Classes

查看:134
本文介绍了Java Local Classes中捕获的变量是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本地类说:


此外,本地类可以访问本地变量。但是,
本地类只能访问声明为final的局部变量。
当本地类访问
封闭块的局部变量或参数时,它会捕获该变量或参数。例如,
PhoneNumber构造函数可以访问本地变量numberLength
,因为它被声明为final; numberLength是一个捕获变量。

In addition, a local class has access to local variables. However, a local class can only access local variables that are declared final. When a local class accesses a local variable or parameter of the enclosing block, it captures that variable or parameter. For example, the PhoneNumber constructor can access the local variable numberLength because it is declared final; numberLength is a captured variable.

什么是捕获变量,它的用途是什么以及为什么需要它?请帮助我理解它的概念。

What is captured variable,what is its use and why is that needed? Please help me in understanding the concept of it.

推荐答案


什么是捕获变量,它是什么使用以及为什么需要?

What is captured variable,what is its use and why is that needed?

捕获的变量是已经复制的变量,因此可以在嵌套类中使用。它必须被复制的原因是对象可能超出当前上下文。它必须是 final (或者在Java 8中有效地 final )所以对变量是否变化没有混淆将会看到(因为它们不会)

A captured variable is one that has been copied so it can be used in a nested class. The reason it has to be copied is the object may out live the current context. It has to be final (or effectively final in Java 8) so there is no confusion about whether changes to the variable will be seen (because they won't)

注意:Groovy确实有这个规则,对局部变量的更改可能意味着更改封闭类中的值如果涉及多个线程,这尤其令人困惑。

Note: Groovy does have this rule and a change to the local variable can mean a change to the value in the enclosing class which is especially confusing if multiple threads are involved.

捕获变量的一个例子。

public void writeToDataBase(final Object toWrite) {
    executor.submit(new Runnable() {
        public void run() {
             writeToDBNow(toWrite);
        }
    });
    // if toWrite were mutable and you changed it now, what would happen !?
}
// after the method returns toWrite no longer exists for the this thread...

这篇关于Java Local Classes中捕获的变量是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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