boolean NPE 问题解决
NPE:NullPointerException(空指针异常)
一、问题再现
Boolean condition = null;
if (condition) {
System.out.println("condition = " + condition);
}
.
二、解决
使用 Boolean.TRUE.equals(xxx)
或者 Boolean.FALSE.equals(xxx)
来代替直接使用 xxx
Boolean condition = null;
if (Boolean.TRUE.equals(condition)) {
System.out.println("condition = " + condition);
}
三、说明
Boolean equals 源码:
.
举例:
Boolean.TRUE.equals(true)
=> true
Boolean.TRUE.equals(false)
=> false
Boolean.TRUE.equals(null)
=> false
Boolean.FALSE.equals(true)
=> false
Boolean.FALSE.equals(false)
=> true
Boolean.FALSE.equals(null)
=> false