gpt4 book ai didi

java - 什么是 Java 本地类中的捕获变量

转载 作者:太空狗 更新时间:2023-10-29 22:45:18 26 4
gpt4 key购买 nike

Local Classes 的 Java 文档说:

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?

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

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

捕获变量的例子。

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 - 什么是 Java 本地类中的捕获变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22025161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com