我有以下代码:
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 许可协议
当你有一个
boolean
它可以是true
或false
。 Yet when you have aBoolean
it can be eitherBoolean.TRUE
,Boolean.FALSE
ornull
as any other object.In your particular case, your
Boolean
isnull
and theif
statement triggers an implicit conversion toboolean
that produces theNullPointerException
。您可能需要: