Optional解决链式调用NPE问题
1.map()
public class Main {
public static void main(String[] args) {
Person person = new Person();
Info personInfo =new Info();
int result;
// 1.PersonInfo 为空
person.setPersonInfo(null);
result = Optional.ofNullable(person)
.map(Person::getPersonInfo)
.map(Info::getAge)
.orElse(-1);
System.out.println("PersonInfo为空, result is " + result);
//2.PersonInfo.age 为空
person.setPersonInfo(personInfo);
result = Optional.ofNullable(person)
.map(Person::getPersonInfo)
.map(Info::getAge)
.orElse(-1);
System.out.println("PersonInfo.age为空, result is " + result);
// 3.非空
personInfo.setAge(1);
person.setPersonInfo(personInfo);
result = Optional.ofNullable(person)
.map(Person::getPersonInfo)
.map(Info::getAge)
.orElse(-1);
System.out.println("非空, result is " + result);
}
}
结果:
2.filter()
public void setName(String name) throws IllegalArgumentException {
this.name = Optional.ofNullable(name).filter(User::isNameValid)
.orElseThrow(()->new IllegalArgumentException("Invalid username."));
}