以下代码在第 1 行
The blank final field name may not have been initialized
我的问题是为什么会出现这个错误,因为我已经在其构造函数中初始化了字段。
public class Test1 {
private final String name;
public Test1() {
name = "abc";
}
@SuppressWarnings("rawtypes")
private final Function fs = n -> {
System.out.println(this.name);// Line 1
return n;
};
public static void main(String[] args) {
new Test1();
}
}
最佳答案
在对象创建过程中,实例初始化器(即对实例变量和初始化 block 的赋值)在构造函数运行之前执行,因此,它们需要在那时初始化值。以下应该有效:
public class Test1 {
private final String name;
public Test1() {
name = "abc";
fs = n -> {
System.out.println(this.name);// Line 1
return n;
};
}
@SuppressWarnings("rawtypes")
private final Function fs;
public static void main(String[] args) {
new Test1();
}
}
关于java - The blank final field name may not have been initialized 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44798657/