来自 Oracle 的 guide ,初始化字段(强调我的):
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
此外,来自 DOJ 的 article关于 Java 中的实例初始值设定项(重点是我的):
Instance initialization block code runs right after the call to super() in a constructor, in other words, after all super constructors have run.
考虑到这一点,为什么每次我尝试在实例初始化程序 block 中使用(分配的)final 字段时,编译器都会向我发出警告,如下所示?
final class PpTitleBook implements TitleBook {
private final Resources resources;
private final Log log;
PpTitleBook(Resources resources, Log log) {
this.resources = resources;
this.log = log;
}
{
String[] resTitles = resources.getStringArray(R.array.titles);
if (book().getAllKeys().isEmpty()) {
for (int i = 0; i < resTitles.length; i++) {
newTitle(resTitles[i]);
}
}
}
除了上面显示的构造函数之外,我没有其他构造函数。那么警告背后的真正原因是什么?
最佳答案
实例初始化 block 代码在构造函数代码之前执行,因此您的 resources
变量在被实例初始化 block 使用之前不会被初始化。
由于您只有一个构造函数,因此您只需将实例初始值设定项 block 的代码移至构造函数即可。
关于java - 为什么我不能在实例初始化 block 中使用 Final 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36356948/