避免未初始化的非最终成员 class/ class 变量

Avoid uninitialized non final member class/ class variable

我发现 Java 编译器没有完全涵盖防止忘记初始化对象 and/or Sonar 警告,我正在使用带有最新 Sonar 插件的最新 Eclipse。

我缺少 error/warning 关于不初始化的信息,例如 Map(同样可以是 String

在示例 Class Variable mapStatic and Member Variable map 中,既是私有的又不是最终的,可以在没有初始化的情况下声明,并且没有关于 NullPointerException 的任何 error/warning。

虽然对于局部变量 mapVar 我得到编译错误 Compile The local variable mapVar may not have been initialized

显然是局部变量 are not assign with default value,但为什么 compiler/sonar 不警告 NullPointerException?

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable.

private static Map<String, String> mapStatic; // Missing compile/warning
private Map<String, String> map; // Missing compile/warning
public void  put() {
    map.put("x", "1"); // NullPointerException
    //Map<String, String> mapVar;
    //mapVar.put("x", "1"); // Compile The local variable mapVar may not have been initialized
}
static {
    mapStatic.put("x", "1"); // NullPointerException        
}

此外,如果我添加 final,我将得到编译错误 Compile The local variable map may not have been initialized

我发现an answer它不会在编译时,那么如何避免或预先发现这个问题?

Failing to initialise a value is a logic error on the part of the programmer, and should be caught as soon as possible. Java does this at compile time for locals, but only at runtime (or not at all) for fields.

您似乎正在寻找的行为更有可能产生不必要的警告,而不是帮助设计。

class 级字段获得 JVM 分配的默认值这一事实是设计使然,并且出于多种原因这是可以的,包括:

  • 有可能在对象构造之后才知道该字段的值。这是典型的,因为许多字段值仅在 setters.
  • 中设置
  • 有可能现在的class本身并不知道这个值是多少。在这种情况下,设置值的责任在 class 之外,因此警告只会让人烦恼。
  • 如果该字段根本不会在当前 class 中使用怎么办?

这是开发人员的责任范围。只有你知道执行顺序,只有你知道代码依赖什么数据,只有你有责任测试代码并确保它没有错误。