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

public final class OptionalChainedUtils {

    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  OptionalChainedUtils of(T value) {
        return new OptionalChainedUtils<>(value);
    }

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

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

    public  OptionalChainedUtils getBean(Function 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 other) {
        return value != null ? value : other.get();
    }

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

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

    public void ifPresent(Consumer consumer) {
        if (value != null){
            consumer.accept(value);
        }

    }

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


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

}

你可能感兴趣的:(java,开发语言)