1. 程式人生 > >JAVA8之妙用Optional解決NPE問題

JAVA8之妙用Optional解決NPE問題

例子1:

//傳統寫法

if (user != null){

// TODO: do something

}

//java8寫法

Optional.ofNullable(user).ifPresent(u->{

// TODO: do something

});

例子2:
/*****
    *
    * 使用Optional解決NPE(空指標異常)
    * @author chenmc
    * @date 2018/8/2 0:34
    * @param user
    * @return cn.tdw.modules.kefu.dto.CallLogDto
    */

//傳統寫法:

public CallLogDto getUser(CallLogDto user) throws Exception{
    if(user!=null){

        if("zhangsan".equals(user.getIntention())){
            return user;
        }
    }else{
        user = new CallLogDto();
        user.setIntention("zhangsan");
        return user;
    }
}


//java8寫法

public CallLogDto getUser(CallLogDto user) {
    return Optional.ofNullable(user)
        .filter(u->"zhangsan".equals(u.getIntention()))
        .orElseGet(()-> {
            CallLogDto user1 = new CallLogDto();
            user1.setIntention("zhangsan");
            return user1;
        });
}