gpt4 book ai didi

java - 在没有初始化器的情况下将局部变量声明为 final 并在 if 语句中分配

转载 作者:搜寻专家 更新时间:2023-10-30 19:40:05 25 4
gpt4 key购买 nike

我只是做了一个小的代码更改以消除 FindBugs 警告,该警告需要将一些代码移动到匿名内部类。为了访问一些变量,我必须将它们声明为 final。所以这是更改后的代码片段:

final File[] libPath; // libPath is final but assignment takes place later
if (libraryPath != null) {
libPath = pathToFiles(libraryPath);
} else {
libPath = new File[0];
}

在当前 Eclipse(版本 3.7.1)中将语言设置为 Java 6 时编译效果很好。但是我很确定这曾经在某些以前的版本中出错。似乎编译器在确定存在时会接受此构造。

我的问题是:这在 Java 6 中是否合法,或者由于 Java 7 支持被添加到 eclipse 3.7.1 的副作用,它现在可以工作了吗?我们已经看到在 3.7.1 中有效但无法在 3.7.0 中编译的泛型的某些用法的此类副作用。

最佳答案

没关系。它被称为blank final

引自维基:

A final variable can only be initialized once, either via an initializer or an assignment statement. It need not be initialized at the point of declaration: this is called a "blank final" variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared: otherwise, a compile-time error occurs in both cases. [4] (Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.)

Blank final

The blank final, which was introduced in Java 1.1, is a final variable whose declaration lacks an initializer. [5][6] A blank final can only be assigned once and must be unassigned when an assignment occurs. In order to do this, a Java compiler runs a flow analysis to ensure that, for every assignment to a blank final variable, the variable is definitely unassigned before the assignment; otherwise a compile-time error occurs.[7]

In general, a Java compiler will ensure that the blank final is not used until it is assigned a value and that once assigned a value, the now final variable cannot be reassigned another value.[8]

链接:http://en.wikipedia.org/wiki/Final_%28Java%29

关于java - 在没有初始化器的情况下将局部变量声明为 final 并在 if 语句中分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8911854/

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