在程序中必须进行严格的判空处理,避免对空对象的异常操作。
lombok 集成了较为完善的空值校验方法,且使用简单,建议使用。
引入 lombok 依赖:
<!--Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
使用 import cn.hutool.core.util.StrUtil;
String 类型不能用 == null
来判空,String 类型的排除空值的情况有如下几种:
(1)排除 String 值为 null 、空字符串,使用 StrUtil.isEmpty() 方法。
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() 方法。
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、空字符串、空格");
}
包装类 Integer、Long、Double 等包装类型的判空同一般类对象判空相同,使用 == null
。
Long studentId = new Long();
if (null == studentId) {
throw new RuntimeException("Long对象不能为空");
}
类对象的判空用 ==null
就足够了。
Student student = new Student();
if (null == student) {
throw new RuntimeException("类对象不能为空");
}
简洁方案,使用 Optional 工具:
import java.util.Optional;
Optional.ofNullable(device).orElseThrow(() -> new RuntimeException("类对象不能为空"));
使用 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
使用 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
// 远程调用,查询用户角色
String roleCode = RetOps.of(remoteUserService.getRoleCodeByUserId(SecurityUtils.getUserId(), SecurityConstants.FROM_IN)).getData()
.orElseThrow(() -> new ServiceException("用户信息查询失败"));