java提供用以解决空指针问题。
常用方法
map: 映射
filter:过滤
orElse:获取Bean属性,没有则给定默认值
orElseGet:获取Bean属性,没有则给定默认值,并执行其他操作
orElseThrow:获取Bean属性,没有则抛出异常
ifPreset:获取Bean属性,如果存在则执行操作
实例
try{
// orElse
Integer age = Optional.ofNullable(student).map(Student::getBasePersonInfo)
.map(BasePersonInfo::getAge).orElse(18);
// orElseGet
Integer age2 = Optional.ofNullable(student).map(Student::getBasePersonInfo)
.map(BasePersonInfo::getAge).orElseGet(() -> {
log.error("age not exist");
return 18;
});
// orElseThrow
Optional.ofNullable(student).map(Student::getBasePersonInfo).map(BasePersonInfo::getAge)
.filter(value->value>=18).orElseThrow(()->new Exception("age under 18"));
// ifPreset
Optional.ofNullable(student).map(Student::getBasePersonInfo).map(BasePersonInfo::getAge)
.ifPresent(Demo::checkValue);
}catch (Exception e){
log.error(e.getMessage());
}