Java中对象判空一行代码处理(optional方式)

问题

BigDecimal yearValue = BigDecimal.ZERO;
BigDecimal value = item.getValue();
if (value != null){
    // 使用value对象实例进行业务处理
    yearValue.add(value);
}

这里对value对象实例进行判空处理,这里需要减少此处的代码行数。

思路

使用Java中的Optional类中ofNullable方法和orElse方法来减少上述判空逻辑函数。这2个方法注解一下:

    /**
     * Returns an {@code Optional} describing the specified value, if non-null,
     * otherwise returns an empty {@code Optional}.
     *
     * @param  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);
    }

    /**
     * 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;
    }
  • Optional ofNullable(T value):主要是将传入的对象转化成Optional对象。如果传入的对象,为空,则返回Optional.empty(),如果对象不为空,则将传入的对象转化成Optional对象;
  • T orElse(T other):如果Optional对象中的value为空,则返回传入的other对象,如果Optional对象中的value为步空,则返回Optional对象中的value。

解决:

// 如果item.getValue()对象为空,则返回BigDecimal.ZERO;如果item.getValue()对象不为空,则返回item.getValue()对象。
BigDecimal yearValue = BigDecimal.ZERO;
yearValue.add(Optional.ofNullable(item.getValue()).orElse(BigDecimal.ZERO));

总结

以后可以使用一行Optional方式处理对象判空了。

你可能感兴趣的:(java)