《空指针》Optional解决链式调用NPE问题

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

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."));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值