Java8 Optional多层嵌套循环取值避免空指针

Java8 Optional多层嵌套循环取值避免空指针


/**
 * Optional避免空指针,采用默认值或者自定义抛出异常
 * 使用场景:多层对象嵌套取值
 * 
 * 
 **/
public class OptionalTest {
     

    @Test
    public void Test1() {
     
        // 正常情况,都不为null,都可以正常执行
        User user = User.builder().address( Address.builder()
                .country( Country.builder().countryName( "nj" )
                        .build() )
                .build() )
                .build();

        // user为null
        user = null;

        // Address 为null
        user = User.builder().address( null ).build();

        // country 为null
        user = User.builder().address( Address.builder()
                .country( null ).build() ).build();
        
        OptTest( user );

    }

    public void OptTest(User user) {
     

        // 第一种方式:存在空指针的风险,只要与一个对象为空就会空指针
        String countryName = user.getAddress().getCountry().getCountryName();
        System.out.println( "第一种方式:" + countryName );

        // 第二种方式:各种if判断避免了空指针,但是if层级太深,代码冗长
        if (user != null) {
     
            Address address = user.getAddress();
            if (address != null) {
     
                Country country = address.getCountry();
                if (country != null) {
     
                    String couName = country.getCountryName();
                    System.out.println( "第二种方式:" + couName );
                }
            }
        }

        // 第三种方式:代码简洁,避免空指针,武林那一步为空都会返回默认值
        String counName = Optional.ofNullable( user )
                .map( User::getAddress )
                .map( Address::getCountry )
                .map( Country::getCountryName )
                .orElse( "china" );
        System.out.println( "第三种方式:" + counName );

        // 第三种方式:代码简洁,避免空指针,武林那一步为空都会返回自定义异常
        String countryNameEx = Optional.ofNullable( user )
                .map( User::getAddress )
                .map( Address::getCountry )
                .map( Country::getCountryName )
                .orElseThrow( () -> new RuntimeException( "countryId is null" ) );
        System.out.println( "第四种方式:" + countryNameEx );
    }

}


/**
 * @author zrj
 * @version V1.0
 * @since 2020/11/20
 **/
@Data
@Builder
public class User {
     
    private Integer userId;

    private String userName;

    private Address address;
}

@Data
@Builder
public class Address {
     
    private Integer addressId;

    private String addressName;

    private Country country;
}

@Data
@Builder
public class Country {
     
    private Integer countryId;

    private String countryName;
}

你可能感兴趣的:(基础框架)