在 Java 中,“空值”通常指 null,但不同数据类型判断方式略有区别。下面按常见情况给你总结一下。
if (obj == null) {
// 对象为空
}
if (obj != null) {
// 对象不为空
}
⚠️ 注意:不能用 == 判断字符串内容,只能判断引用。
if (str == null) {
}
if (str != null && str.isEmpty()) {
}
if (str == null || str.isEmpty()) {
}
if (str == null || str.trim().isEmpty()) {
}
if (str == null || str.isBlank()) {
}
if (list == null) {
}
if (list != null && list.isEmpty()) {
}
if (list == null || list.isEmpty()) {
}
if (arr == null || arr.length == 0) {
}
Optional<String> opt = Optional.ofNullable(str);
if (opt.isPresent()) {
// 不为空
}
// 或
opt.ifPresent(value -> {
// 不为空时执行
});
if (str.equals(null)) // ❌ 会空指针
✅ 正确:
if (str == null)
StringUtils.isEmpty(str);
StringUtils.isBlank(str);
ObjectUtils.isEmpty(obj);
如果你有具体场景(比如方法参数、数据库返回值、JSON 解析),我可以给你更合适的写法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。