JDK1.8 Optional关键字

在工作中,经常会处理各种变量,但往往会在使用变量的时候,要进行非空判断,
否则就会出现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

项目源码

后端代码前端代码
githubhttps://github.com/zengfen0708/easy-boothttps://github.com/zengfen0708/easy-boot-web
码云https://gitee.com/zf0708/easyboothttps://gitee.com/zf0708/easy-boot-web
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值