在工作中,经常会处理各种变量,但往往会在使用变量的时候,要进行非空判断,
否则就会出现java.lang.NullPointerException。
在Java 8中提供一个更加优雅处理Null指针错误方式
//如果查询的用户为空,则直接报对应未找到用户错误
UserEntity user = userMapper.findByUsername(username)
.orElseThrow(() -> new
UsernameNotFoundException("未找到用户信息 : "
+ username));
//jdk1.7写法
if(user==null){
throw UsernameNotFoundException("未找到用户信息 : "
}
或者下面使用方法
public Date localDateConvert(LocalDate localDate) {
//如果当前参数未传递值,则使用默认值 jdk1.8写法
LocalDate currentDate = Optional.ofNullable(localDate).orElse(LocalDate.now());
//jdk1.7写法
LocalDate currentDate = LocalDate.now()
if (localDate == null) {
currentDate = localDate
}
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdf = currentDate.atStartOfDay(zoneId);
return Date.from(zdf.toInstant());
}
注意
Optional 只能处理为null.如果是字符串这种""是不支持的
关于具体用法可以采用我的开源项目easy-boot
项目源码
后端代码 | 前端代码 | |
---|---|---|
github | https://github.com/zengfen0708/easy-boot | https://github.com/zengfen0708/easy-boot-web |
码云 | https://gitee.com/zf0708/easyboot | https://gitee.com/zf0708/easy-boot-web |