以下是一些常用的类和方法,可用于检查对象、字符串、数组等是否为空。
使用Apache Commons Lang库的ObjectUtils
类
import org.apache.commons.lang3.ObjectUtils;
Object obj = null;
if (ObjectUtils.isEmpty(obj)) {
// obj 为空
} else {
// obj 不为空
}
使用Objects.isNull()
方法
import java.util.Objects;
Object obj = null;
if (Objects.isNull(obj)) {
// obj 为空
} else {
// obj 不为空
}
使用Guava库的Objects
类
import com.google.common.base.Objects;
Object obj = null;
if (Objects.equal(obj, null)) {
// obj 为空
} else {
// obj 不为空
}
使用Apache Commons库的StringUtils
类
import org.apache.commons.lang3.StringUtils;
String str = null;
if (StringUtils.isEmpty(str)) {
// str 为空
} else {
// str 不为空
}
使用Apache Commons库的ArrayUtils
类
import org.apache.commons.lang3.ArrayUtils;
Object[] array = null;
if (ArrayUtils.isEmpty(array)) {
// array为空
} else {
// array不为空
}