遇到的问题之“对象不为空,字段为空,取出使用时报空指针异常【特例场景:Optional的使用】”
一、场景
二、原因
目前找到的原因是:使用Optional.of()方法对其判空后直接报错了,就没有走orElse了
Optional.of()源码
Optional.java
/** * Returns an {@code Optional} with the specified present non-null value. * * @param <T> the class of the value * @param value the value to be present, which must be non-null * @return an {@code Optional} with the value present * @throws NullPointerException if value is null */ public static <T> Optional<T> of(T value) { return new Optional<>(value); }
/** * Constructs an instance with the value present. * * @param value the non-null value to be present * @throws NullPointerException if value is null */ private Optional(T value) { this.value = Objects.requireNonNull(value); }
Objects.java
/** * Checks that the specified object reference is not {@code null}. This * method is designed primarily for doing parameter validation in methods * and constructors, as demonstrated below: * <blockquote><pre> * public Foo(Bar bar) { * this.bar = Objects.requireNonNull(bar); * } * </pre></blockquote> * * @param obj the object reference to check for nullity * @param <T> the type of the reference * @return {@code obj} if not {@code null} * @throws NullPointerException if {@code obj} is {@code null} */ public static <T> T requireNonNull(T obj) { if (obj == null) throw new NullPointerException(); return obj; }
三、解决方案
改用:Optional.ofNullable()
这个方案就直接判空返回,并不会直接报错,返回fasle后
Optional.ofNullable()源码
Optional.java
/** * 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); }
这里使用了@SuppressWarnings("unchecked"):忽略 unchecked 警告
/** * Common instance for {@code empty()}. */ private static final Optional<?> EMPTY = new Optional<>();
/** * Returns an empty {@code Optional} instance. No value is present for this * Optional. * * @apiNote Though it may be tempting to do so, avoid testing if an object * is empty by comparing with {@code ==} against instances returned by * {@code Option.empty()}. There is no guarantee that it is a singleton. * Instead, use {@link #isPresent()}. * * @param <T> Type of the non-existent value * @return an empty {@code Optional} */ public static<T> Optional<T> empty() { @SuppressWarnings("unchecked") Optional<T> t = (Optional<T>) EMPTY; return t; }
* 博客文章部分截图及内容来自于学习的书本及相应培训课程,仅做学习讨论之用,不做商业用途。
* 如有侵权,马上联系我,我立马删除对应链接。
* 备注:王子威
* 我的网易邮箱:wzw_1314_520@163.com