Java中Optional类及orElse方法详解

2022-09-03 15:28:05 64 0
魁首哥

目录

  • 引言
  • Java 中的 Optional 类
    • ofNullable() 方法
    • orElse() 方法
      • 案例
    • orElseGet() 方法
      • 案例
    • orElse() 与 orElseGet() 之间的区别

    引言

    为了让我更快的熟悉代码,前段时间组长交代了一个小任务,大致就是让我整理一下某个模块中涉及的 sql,也是方便我有目的的看代码,也是以后方便他们查问题(因为这个模块,涉及的判断很多,所以之前如果 sql 出错了,查问题比较繁琐)。

    Java中Optional类及orElse方法详解

    昨天算是基本完成了,然后今天组长就让给我看一个该模块的缺陷,由于刚对该模块进行过整理,所以还算清晰......看代码过程中,看到一些地方进行判空时都用到了 orElse() 方法,之前没怎么用过,熟悉一下......

    Java 中的 Optional 类

    Optional 类是 Java8 为了解决 NULL 值判断等问题提出的。使用 Optional 类可以避免显式的判断 NULL 值(NULL 的防御性检查),避免某一处因为出现 NULjavascriptL 而导致的 NPE(NullPointerException)。

    ofNullable() 方法

    /**
     * A container object which may or may not contain a non-null value.
     * If a value is present, {@code isPresent()} will return {@code true} and
     * {@code get()} will return the value.
     */
     public final class Optional<T> {
    
        /**
         * Common instance for {@code empty()}.
         */
        private static final Optional<?> EMPTY = new Optional<>(); //执行Optional的无参构造
        
    	//无参构造
    	private Optional() {
      编程      this.value = null;
        }
        //有参构造
        private Optional(T value) {
            this.value = Objects.requireNonNull(value);
        }
        /**
         * Returns an {@code Optional} describing the specified value, if non-null,
         * otherwise returns an empty {@code Optional}.
         * 如果value不是null, 返回它自己本身, 是空, 则执行empty(), 返回null
         *
         * @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.
         * 当value是空时, 返回Optional<T>对象
         *
         * @apiNote Thttp://www.cppcns.comhough 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;  //由第一行代码可知, EMPTY是一个无参Optionwww.cppcns.comal对象
            return t;
        }
       
        /**
         * Returns an {@code Optional} with the specified present non-null value.
         * 返回不等于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);  //执行Optional的有参构造
        }
     }
    

    从源码中可以看出来,ofNullable() 方法做了 NULL 值判断,所以我们可以直接调用该方法进行 NULL 值判断,而不用自己手写 NULL 值判断。

    orElse() 方法

        /**
         * Return the value if present, otherwise return {@code other}.
         * 如果值存在(即不等于空), 返回值本身, 如果等于空, 就返回orElse()方法的参数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;
        }
    

    从源码中可以看出,调用 orElse() 方法时,当值为 NULL 值,返回的是该方法的参数;当值不为 NULL 时,返回值本身。

    案例

    Optional.ofNullable(scRespDTO.getMsgBody().getSuccess()).orElse(false);
    

    上述案例中,如果 ofNullable() 方法执行结果不为 NULL,则返回 scRespDTO.getMsgBody().getSuccess() 的值;

    如果 ofNullable() 方法的执行结果是 NULL,则返回 false,即,orElse() 方法的参数。

    orElseGet() 方法

        /**
         * Return the value if present, otherwise invoke {@code other} and return
         * the result of that invocation.
         * 值如果存在(即不为空), 返回值本身, 如果不存在, 则返回实现了Supplier接口的对象. 
         * Supplier接口就只有一个get()方法. 无入参,出参要和Optional的对象同类型.
         *
         * @param other a {@code Supplier} whose result is returned if no value
         * is present
         * @return the value if present otherwise the result of {@code other.get()}
         * @throws NullPointerException if value is not present and {@code other} is
         * null
         */
        public T orElseGet(Supplier<? extends T> other) {
            return value != null ? value : other.get();
        }
    

    从源码中可以看出来,调用 orElseGet() 方法时,如果值为 NULL,返回的是实现了 Supplier 接口的对象的 get() 值;

    如果值不为 NULL,则返回值本身。

    案例

    System.out.println(Optional.ofNullable("努力成为一名更优秀的程序媛").orElseGet(()->"你不够优秀"));
    System.out.println(Optional.ofNullable(null).orElseGet(()->"你没有努力"));  
    

    orElseGet() 可以传入一个supplier接口,里面可以花样实现逻辑。

    上述案例中,第一句,ofNullable() 不为 NULL,就输出"努力成为一名更优秀的程序媛",反之,则输出"你不够优秀";

    第二句,ofNullable() 为 NULL, 输出 "你没有努力"。

    orElse() 与 orElseGet() 之间的区别

    注意

    orElse() 与 orElseGet() 两者之间是 有区别 的。虽然当值为 NULL 时,orElse() 与 orElseGet() 都是返回方法的参数,但区别就是:orElse() 方法返回的是参数本身,而 orElseGet() 方法并不是直接返回参数本身,而是返回 参数的 get() 值,且 该参数对象必须实现 Supplier 接口(该接口为函数式接口)。这就使得 orElseGet() 方法更加灵活。

    简单做了一下 Java 中 Optional 类以及其中的 orElse() 方法 与 orElseGet() 方法相关的内容,以前没有了解过。文中显然引入了许多源码,也是为了方便理解不是? :)

    以上就是Java中Optional类及orElse()方法详解的详细内容,更多关于Java Optional类 orElse()方法的资料请关注我们其它相关文章!

    收藏
    分享
    海报
    0 条评论
    64
    上一篇:Awaitility同步异步工具实战示例详解 下一篇:Java redis使用场景介绍

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码