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."));
}
文章通过示例展示了如何在Java中利用Optional类的map()和filter()方法来避免NullPointerException(NPE)。在链式调用中,Optional.ofNullable()用于包装可能为null的对象,map()和filter()方法在对象不存在时返回默认值或抛出异常,确保代码的健壮性。

901

被折叠的 条评论
为什么被折叠?



