java8使用Optional来避免空指针异常(简化代码)

在最近的开发中遇到不少java.lang.NullPointerException异常 ,而为了避免这个异常,不免要利用if-else来进行判断。比如如下的代码:

    public static void main(String[] args)
    {
        List<String> fruits = getFruits();
        if(fruits != null)
        {
            // To do
            fruits.forEach(fruit -> System.out.println(fruit));
        }
   }

我们打算对fruits利用增强for循环遍历,那如果没有判空的话,就会抛出空指针异常。

明明就是很简单的逻辑,却一定要有一个if来判空,越想越觉得难受。后来突然发现原来java8中已经新增了特性帮助我们解决这个问题,那就是Optional类。先瞅一眼这Optional类是个啥:

public final class Optional<T> {
    /**
     * Common instance for {@code empty()}.
     */
    private static final Optional<?> EMPTY = new Optional<>();

    /**
     * If non-null, the value; if null, indicates no value is present
     */
    private final T value;

简单看一眼源码,Optional里面有一个final修饰的泛型变量,就应该是我们使用Optional的关键变量了。

接下来看一下,针对最开始的问题,使用Optional应该怎样解决呢:

    public static void main(String[] args)
    {
        List<String> fruits = getFruits();
        if(fruits != null)
        {
            // To do
            // fruits.forEach(fruit -> System.out.println(fruit));
            Optional.ofNullable(fruits).orElse(Collections.emptyList()).forEach(fruit -> System.out.println(fruit));
        }
    }

这里有两个方法,ofNullable(),以及orElse(),我们首先看ofNullable()源码:

    /**
     * Returns an {@code Optional} describing the specified value, if non-null,
     * otherwise returns an empty {@code Optional}.
     *
     * @param <T> the class of the value
     * @param value the possibly-null value to describe
     * @return an {@code Optional} with a present value if the specified value
     * is non-null, otherwise an empty {@code Optional}
     */
    public static <T> Optional<T> ofNullable(T value) {
        return value == null ? empty() : of(value);
    }

很简单,判断参数是否为空,返回一个value为empty的Optional对象 或者 value为参数的Optional对象

然后是orElse():

    /**
     * Return the value if present, otherwise return {@code other}.
     *
     * @param other the value to be returned if there is no value present, may
     * be null
     * @return the value, if present, otherwise {@code other}
     */
    public T orElse(T other) {
        return value != null ? value : other;
    }

这里,可以看到,对于刚才利用ofNullable()获得的对象,我们判断它是不是为空,如果是空,可以人为传进去一个参数,比如最开始的例子,传了一个Collections.emptyList();否则,value值保持不变。

这样一来,我们获得了一个value是我们想要的值的Optional实例,之后使用forEach就可以放心的遍历而不需要担心空指针异常了。

猜你喜欢

转载自blog.csdn.net/VeastLee/article/details/83273071