Java 中的 if(null) 语句 return 会怎样?

What if(null) statement return in Java?

我有一个 method,它有一个 Boolean parameter,例如:

public void method(Boolean parameter){
...
}

我可以只用if(parameter)判断逻辑吗? 如果 parameternull 怎么办?

将您的数据类型从 Boolean 更改为 booleanboolean 是原始数据类型,不能为空。

编译器会把你的

if (parameter)

进入

if (parameter.booleanValue())

通过自动拆箱。所以这应该告诉你 null 会发生什么(一个 NullPointerException,就像你在 null 上调用方法的任何其他时间一样)。

如果你尝试过,你会看到 NullPointerException

但是 Boolean.equals(Object) Javadoc 确实开始了

Returns true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this object.

(我的重点)

所以你可以

if (Boolean.TRUE.equals(parameter)) {
    System.out.println("true");
} else {
    System.out.println("false");
}

我相信这会处理您的 null 案例。