java 判空工具方法大全
前言
在程序中必须进行严格的判空处理,避免对空对象的异常操作。
- 接收对象或对象属性的空值校验。
- 查询对象为空时,获取对象属性的空指针异常。
- 对空 list、set 进行操作,产生的空指针异常。
- 如此等等。
lombok 集成了较为完善的空值校验方法,且使用简单,建议使用。
引入 lombok 依赖:
<!--Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
一、一般类型的判空
1、String 类型判空
使用 import cn.hutool.core.util.StrUtil;
String 类型不能用 == null
来判空,String 类型的排除空值的情况有如下几种:
- null
- 空字符串
- 空格
(1)排除 String 值为 null 、空字符串,使用 StrUtil.isEmpty() 方法。
- 排除 null
- 排除 空字符串
import cn.hutool.core.util.StrUtil;
String str = new String();
StrUtil.isEmpty(str); // true
StrUtil.isNotEmpty(str) // false
if (StrUtil.isEmpty(str)) {
throw new RuntimeException("字符串不能为null、空字符串");
}
(2)排除 String 值为 null 、空字符串、空格,使用 StrUtil.isBlank() 方法。
- 排除 null
- 排除 空字符串
- 排除 空格
import cn.hutool.core.util.StrUtil;
String str = new String();
StrUtil.isBlank(str); // true
StrUtil.isNotBlank(str) // false
if (StrUtil.isBlank(str)) {
throw new RuntimeException("字符串不能为null、空字符串、空格");
}
2、包装类型判空
包装类 Integer、Long、Double 等包装类型的判空同一般类对象判空相同,使用 == null
。
Long studentId = new Long();
if (null == studentId) {
throw new RuntimeException("Long对象不能为空");
}
二、类对象判空
1、类对象判空
类对象的判空用 ==null
就足够了。
Student student = new Student();
if (null == student) {
throw new RuntimeException("类对象不能为空");
}
简洁方案,使用 Optional 工具:
import java.util.Optional;
Optional.ofNullable(device).orElseThrow(() -> new RuntimeException("类对象不能为空"));
三、容器类型判空
1、List、Set 判空
使用 import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.CollectionUtil;
List<String> list= new ArrayList<>();
CollectionUtil.isEmpty(list); // true
CollectionUtil.isNotEmpty(list); // false
2、Map 判空
使用 import cn.hutool.core.collection.MapUtil;
import cn.hutool.core.collection.MapUtil;
HashMap<String, Long> map = new HashMap<>();
MapUtil.isEmpty(map); // true
MapUtil.isNotEmpty(map); // false
四、远程调用 R 类对象判空
// 远程调用,查询用户角色
String roleCode = RetOps.of(remoteUserService.getRoleCodeByUserId(SecurityUtils.getUserId(), SecurityConstants.FROM_IN)).getData()
.orElseThrow(() -> new ServiceException("用户信息查询失败"));