--
Optional类是Java8为了解决null值判断问题,使用Optional类可以避免显式的null值判断(null的防御性检查),避免null导致的NPE(NullPointerException)。
示例:
public static void main(String[] args) { TestDemo testDemo = new TestDemo(); getCount(testDemo); } private static void getCount(TestDemo testDemo) { //if判断:判断好多层 int count1 = 1; if(testDemo != null){ if(testDemo.getCount() != null){ count1 = testDemo.getCount(); } } System.out.println(count1); //三目运算符:嵌套层数深,可读性不好 int count2 = testDemo != null ? (testDemo.getCount() != null ? testDemo.getCount() : 1) : 1; System.out.println(count2); //Java8-Optional:优雅,可读性较好 int count3 = Optional.ofNullable(testDemo).map(item -> item.getCount()).orElse(1); System.out.println(count3); } private static class TestDemo { private Integer count; public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } }
源码:
/** * 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); } /** * 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; } /** * 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); }
————————————————
版权声明:本文为CSDN博主「程序小白-M」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zym_1321/article/details/107769743