java 链式操作巧E妙避免空指针异常

public final class OptionalChainedUtils<T> {

    private static final OptionalChainedUtils<?> EMPTY = new OptionalChainedUtils<>();

    private final T value;

    private OptionalChainedUtils() {
        this.value = null;
    }

    private OptionalChainedUtils(T value) {
        this.value = Objects.requireNonNull(value);
    }

    public static <T> OptionalChainedUtils<T> of(T value) {
        return new OptionalChainedUtils<>(value);
    }

    public static <T> OptionalChainedUtils<T> ofNullable(T value) {
        return value == null ? empty() : of(value);
    }

    public T get() {
        return Objects.isNull(value) ? null : value;
    }

    public <R> OptionalChainedUtils<R> getBean(Function<? super T, ? extends R> fn) {
        return Objects.isNull(value) ? OptionalChainedUtils.empty() : OptionalChainedUtils.ofNullable(fn.apply(value));
    }

    /**
     * 如果目标值为空 获取一个默认值
     * @param other
     * @return
     */
    public T orElse(T other) {
        return value != null ? value : other;
    }

    public T orElseGet(Supplier<? extends T> other) {
        return value != null ? value : other.get();
    }

    public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
        if (value != null) {
            return value;
        } else {
            throw exceptionSupplier.get();
        }
    }

    public boolean isPresent() {
        return value != null;
    }

    public void ifPresent(Consumer<? super T> consumer) {
        if (value != null){
            consumer.accept(value);
        }

    }

    @Override
    public int hashCode() {
        return Objects.hashCode(value);
    }


    public static<T> OptionalChainedUtils<T> empty() {
        OptionalChainedUtils<T> none = (OptionalChainedUtils<T>) EMPTY;
        return none;
    }

}

使用的方式:

final Integer integer = OptionalChainedUtils.ofNullable(bs005Resp)
        .getBean(BS005Resp::getPoliceCheck)
        .getBean(BS005Resp.PoliceCheck::getPoliceCheckInfos)
        .getBean(BS005Resp.PoliceCheck.PoliceCheckInfos::getPoliceCheckInfo).getBean(List::hashCode).get();

猜你喜欢

转载自blog.csdn.net/yz18931904/article/details/131089934