Java 不允许在供应商内部使用 final 变量,因为它可能没有被初始化,但在前面加上“(this)”。to 变量使它编译并运行良好。
此外,如果在分配变量之前调用此类供应商会导致 NullPointerException 而不是编译器错误,如果在之后调用则按预期运行。
这种行为是在某处描述的吗?
我正在使用 OpenJDK 1.8.0_151。
例子:
import java.util.function.Supplier;
class Example {
final String str;
Supplier<Integer> test1 = () -> str.length(); // DOES NOT COMPILE
Supplier<Integer> test2 = () -> this.str.length(); // DOES NOT COMPILE
Supplier<Integer> test3 = () -> (this.str).length(); // DOES NOT COMPILE
Supplier<Integer> test4 = () -> (this).str.length(); // OK
Example(String str) {
System.out.println(test4.get()); // NullPointerException
this.str = str;
System.out.println(test4.get()); // OK
}
}
---
javac Example.java
Example.java:7: error: variable str might not have been initialized
Supplier<Integer> test1 = () -> str.length(); // DOES NOT COMPILE
^
Example.java:8: error: variable str might not have been initialized
Supplier<Integer> test2 = () -> this.str.length(); // DOES NOT COMPILE
^
Example.java:9: error: variable str might not have been initialized
Supplier<Integer> test3 = () -> (this.str).length(); // DOES NOT COMPILE
^
3 errors