欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Optional类如何解决NullPointerException异常

程序员文章站 2022-07-10 17:30:53
NullPointerException相信每个JAVA程序员都不陌生,是JAVA应用程序中最常见的异常。之前,Google Guava项目曾提出用Optional类来包装对象从而解决NullPointerException。受此影响,JDK8的类中也引入了Optional类,在新版的SpringData Jpa和Spring Redis Data中都已实现了对该方法的支持。1.emptystatic Optional empty()//返回空的 Optional...

NullPointerException相信每个JAVA程序员都不陌生,是JAVA应用程序中最常见的异常。之前,Google Guava项目曾提出用Optional类来包装对象从而解决NullPointerException。受此影响,JDK8的类中也引入了Optional类,在新版的SpringData Jpa和Spring Redis Data中都已实现了对该方法的支持。

1.empty

static <T> Optional<T> empty()
//返回空的 Optional 实例。
Optional<Insurance> insuranceOptional = Optional.empty();
insuranceOptional.get();

//使用get方法,会抛出java.util.NoSuchElementException: No value present

2.of

static <T> Optional<T> of(T value)
//返回一个指定非null值的Optional。
Optional<Insurance> insuranceOptional = Optional.of(new Insurance());
insuranceOptional.get();

//使用get方法,不会抛出异常

3.ofNullable

static <T> Optional<T> ofNullable(T value)
//如果为非空,返回 Optional 描述的指定值,否则返回空的 Optional。
//相当于empty+of
Optional<Insurance> insuranceOptional = Optional.ofNullable(null); --Optional.empty()
Optional<Insurance> insuranceOptional = Optional.ofNullable(new Insurance());

4.toString()

String toString()
返回一个Optional的非空字符串,用来调试
Optional<Insurance> insuranceOptional = Optional.ofNullable(new Insurance());
System.out.println(insuranceOptional.toString());
//输出:Optional[Insurance{name='picc'}]

5.equals

boolean equals(Object obj)
判断其他对象是否等于 Optional。
Insurance insurance =  new Insurance();
Optional<Insurance> insuranceOptional1 = Optional.ofNullable(insurance);
Optional<Insurance> insuranceOptional2 = Optional.ofNullable(insurance);

System.out.println(insuranceOptional1.equals(insuranceOptional2));
//输出:true

6.filter

Optional<T> filter(Predicate<? super <T> predicate)
//如果值存在,并且这个值匹配给定的 predicate,返回一个Optional用以描述这个值,
//否则返回一个空的Optional。
Optional<Insurance> insuranceOptional = Optional.of(new Insurance());
Insurance insurance = insuranceOptional.filter(i -> i.getName() != null).get();
System.out.println(insurance);
//输出:Insurance{name='picc'}

Optional<Insurance> insuranceOptional = Optional.of(new Insurance());
Insurance insurance = insuranceOptional.filter(i -> i.getName() == null).get(); 
//输出:java.util.NoSuchElementException: No value present       

7.orElse, orElseGet, orElseThrow

T orElse(T other)
如果存在该值,返回值, 否则返回 other。

T orElseGet(Supplier<? extends T> other)
如果存在该值,返回值, 否则触发 other,并返回 other 调用的结果。

<X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
如果存在该值,返回包含的值,否则抛出由 Supplier 继承的异常
Optional<Insurance> insuranceOptional = Optional.of(new Insurance("PICC"));
Insurance insurance = insuranceOptional.orElse(new Insurance("AIX"));
System.out.println(insurance);
//输出:Insurance{name='PICC'}

Optional<Insurance> insuranceOptional = Optional.ofNullable(null);
Insurance insurance = insuranceOptional.orElse(new Insurance("AIX"));
System.out.println(insurance);
//输出:Insurance{name='AIX'}
 
Optional<Insurance> insuranceOptional = Optional.ofNullable(null);
Insurance insurance = insuranceOptional.orElseGet(()->new Insurance("PICC"));
System.out.println(insurance);
//输出:Insurance{name='PICC'} 

Optional<Insurance> insuranceOptional = Optional.ofNullable(null);
Insurance insurance = insuranceOptional.orElseThrow(() -> new RuntimeException("Not have reference"));
System.out.println(insurance);
//输出:java.lang.RuntimeException: Not have reference 

8.isPresent

boolean isPresent()
//如果值存在则方法会返回true,否则返回 false。
Optional<Insurance> insuranceOptional = Optional.ofNullable(null);
System.out.println(insuranceOptional.isPresent());
//输出: false

Insurance insurance =  new Insurance("PICC");
Optional<Insurance> insuranceOptional = Optional.ofNullable(insurance);
System.out.println(insuranceOptional.isPresent());
//输出: true

9.ifPresent

void ifPresent(Consumer<? super T> consumer)
//如果值存在则使用该值调用 consumer , 否则不做任何事情。
Insurance insurance =  new Insurance("PICC");
Optional<Insurance> insuranceOptional = Optional.ofNullable(insurance);
insuranceOptional.ifPresent(System.out::println);
//输出: Insurance{name='PICC'}

10.map

<U>Optional<U> map(Function<? super T,? extends U> mapper)
//如果有值,则对其执行调用映射函数得到返回值。如果返回值不为 null,
//则创建包含映射返回值的Optional作为map方法返回值,否则返回空Optional。
private static String getInsuranceName(Insurance insurance) {
        if (null == insurance)
            return "unknown";
        return insurance.getName();
}

private static String getInsuranceNameByOptional(Insurance insurance) {
    return Optional.ofNullable(insurance).map(Insurance::getName).orElse("unknown");
}

11.flatmap

<U> Optional<U> flatMap(Function<? super T,Optional<U>> mapper)
//如果值存在,返回基于Optional包含的映射方法的值,否则返回一个空的Optional
  • map中获取的返回值自动被Optional包装,即返回值 -> Optional<返回值>
  • flatMap中返回值保持不变,但必须是Optional类型,即Optional<返回值> -> Optional<返回值>
class FlightTicketInfo {

    private String orderNumber;

    public String getOrderNumber() {
        return orderNumber;
    }

}


public class OptionalTest {

    @Test
    public void testMap() {
        FlightTicketInfo flightTicketInfo = null;

        Optional<Optional<String>> s1 = Optional.ofNullable(flightTicketInfo).map(OptionalTest::getOrderNumber);

        Optional<String> s2 = Optional.ofNullable(flightTicketInfo).map(FlightTicketInfo::getOrderNumber);

        Optional<String> s3 = Optional.ofNullable(flightTicketInfo).flatMap(OptionalTest::getOrderNumber);
    }

    private static Optional<String> getOrderNumber(FlightTicketInfo flightTicketInfo) {
        return Optional.ofNullable(flightTicketInfo).map(f -> f.getOrderNumber());
    }

}

本文地址:https://blog.csdn.net/weixin_42868638/article/details/110230138

相关标签: # java8