检查 null Boolean 是否为真导致异常

新手上路,请多包涵

我有以下代码:

 Boolean bool = null;

try
{
    if (bool)
    {
        //DoSomething
    }
}
catch (Exception e)
{
    System.out.println(e.getMessage());
}

为什么我检查布尔变量“bool”会导致异常?当它“看到”它不是真的时,它不应该直接跳过 if 语句吗? 当我删除 if 语句或检查它是否为 NULL 时,异常就会消失。

原文由 Birdman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 497
2 个回答

当你有一个 boolean 它可以是 truefalse 。 Yet when you have a Boolean it can be either Boolean.TRUE , Boolean.FALSE or null as any other object.

In your particular case, your Boolean is null and the if statement triggers an implicit conversion to boolean that produces the NullPointerException 。您可能需要:

 if(bool != null && bool) { ... }

原文由 K-ballo 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您不喜欢额外的空检查:

 if (Boolean.TRUE.equals(value)) {...}

原文由 AvrDragon 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题