Java中Optional類及orElse方法詳解
引言
為了讓我更快的熟悉代碼,前段時(shí)間組長(zhǎng)交代了一個(gè)小任務(wù),大致就是讓我整理一下某個(gè)模塊中涉及的 sql,也是方便我有目的的看代碼,也是以后方便他們查問(wèn)題(因?yàn)檫@個(gè)模塊,涉及的判斷很多,所以之前如果 sql 出錯(cuò)了,查問(wèn)題比較繁瑣)。
昨天算是基本完成了,然后今天組長(zhǎng)就讓給我看一個(gè)該模塊的缺陷,由于剛對(duì)該模塊進(jìn)行過(guò)整理,所以還算清晰......看代碼過(guò)程中,看到一些地方進(jìn)行判空時(shí)都用到了 orElse() 方法,之前沒(méi)怎么用過(guò),熟悉一下......
Java 中的 Optional 類
Optional 類是 Java8 為了解決 NULL 值判斷等問(wèn)題提出的。使用 Optional 類可以避免顯式的判斷 NULL 值(NULL 的防御性檢查),避免某一處因?yàn)槌霈F(xiàn) NULL 而導(dǎo)致的 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<>(); //執(zhí)行Optional的無(wú)參構(gòu)造 //無(wú)參構(gòu)造 private Optional() { this.value = null; } //有參構(gòu)造 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, 返回它自己本身, 是空, 則執(zhí)行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. * 當(dāng)value是空時(shí), 返回Optional<T>對(duì)象 * * @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; //由第一行代碼可知, EMPTY是一個(gè)無(wú)參Optional對(duì)象 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); //執(zhí)行Optional的有參構(gòu)造 } }
從源碼中可以看出來(lái),ofNullable() 方法做了 NULL 值判斷,所以我們可以直接調(diào)用該方法進(jìn)行 NULL 值判斷,而不用自己手寫(xiě) NULL 值判斷。
orElse() 方法
/** * Return the value if present, otherwise return {@code other}. * 如果值存在(即不等于空), 返回值本身, 如果等于空, 就返回orElse()方法的參數(shù)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; }
從源碼中可以看出,調(diào)用 orElse() 方法時(shí),當(dāng)值為 NULL 值,返回的是該方法的參數(shù);當(dāng)值不為 NULL 時(shí),返回值本身。
案例
Optional.ofNullable(scRespDTO.getMsgBody().getSuccess()).orElse(false);
上述案例中,如果 ofNullable() 方法執(zhí)行結(jié)果不為 NULL,則返回 scRespDTO.getMsgBody().getSuccess() 的值;
如果 ofNullable() 方法的執(zhí)行結(jié)果是 NULL,則返回 false,即,orElse() 方法的參數(shù)。
orElseGet() 方法
/** * Return the value if present, otherwise invoke {@code other} and return * the result of that invocation. * 值如果存在(即不為空), 返回值本身, 如果不存在, 則返回實(shí)現(xiàn)了Supplier接口的對(duì)象. * Supplier接口就只有一個(gè)get()方法. 無(wú)入?yún)?,出參要和Optional的對(duì)象同類型. * * @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(); }
從源碼中可以看出來(lái),調(diào)用 orElseGet() 方法時(shí),如果值為 NULL,返回的是實(shí)現(xiàn)了 Supplier 接口的對(duì)象的 get() 值;
如果值不為 NULL,則返回值本身。
案例
System.out.println(Optional.ofNullable("努力成為一名更優(yōu)秀的程序媛").orElseGet(()->"你不夠優(yōu)秀")); System.out.println(Optional.ofNullable(null).orElseGet(()->"你沒(méi)有努力"));
orElseGet() 可以傳入一個(gè)supplier接口,里面可以花樣實(shí)現(xiàn)邏輯。
上述案例中,第一句,ofNullable() 不為 NULL,就輸出"努力成為一名更優(yōu)秀的程序媛",反之,則輸出"你不夠優(yōu)秀";
第二句,ofNullable() 為 NULL, 輸出 "你沒(méi)有努力"。
orElse() 與 orElseGet() 之間的區(qū)別
注意
orElse() 與 orElseGet() 兩者之間是 有區(qū)別 的。雖然當(dāng)值為 NULL 時(shí),orElse() 與 orElseGet() 都是返回方法的參數(shù),但區(qū)別就是:orElse() 方法返回的是參數(shù)本身,而 orElseGet() 方法并不是直接返回參數(shù)本身,而是返回 參數(shù)的 get() 值,且 該參數(shù)對(duì)象必須實(shí)現(xiàn) Supplier 接口(該接口為函數(shù)式接口)。這就使得 orElseGet() 方法更加靈活。
簡(jiǎn)單做了一下 Java 中 Optional 類以及其中的 orElse() 方法 與 orElseGet() 方法相關(guān)的內(nèi)容,以前沒(méi)有了解過(guò)。文中顯然引入了許多源碼,也是為了方便理解不是? :)
以上就是Java中Optional類及orElse()方法詳解的詳細(xì)內(nèi)容,更多關(guān)于Java Optional類 orElse()方法的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
java基于swing實(shí)現(xiàn)的五子棋游戲代碼
這篇文章主要介紹了java基于swing實(shí)現(xiàn)的五子棋游戲代碼,主要涉及圖形界面與數(shù)組的用法,有不錯(cuò)的參考借鑒價(jià)值,需要的朋友可以參考下2014-11-11Java?項(xiàng)目連接并使用?SFTP?服務(wù)的示例詳解
SFTP是一種安全的文件傳輸協(xié)議,是SSH(Secure?Shell)協(xié)議的一個(gè)子協(xié)議,設(shè)計(jì)用于加密和保護(hù)文件傳輸?shù)陌踩?這篇文章主要介紹了Java?項(xiàng)目如何連接并使用?SFTP?服務(wù)的示例詳解,需要的朋友可以參考下2025-01-01Jsoup解析html實(shí)現(xiàn)招聘信息查詢功能
這篇文章主要為大家詳細(xì)介紹了Jsoup解析html實(shí)現(xiàn)招聘信息查詢功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04mybatis中foreach報(bào)錯(cuò):_frch_item_0 not found的解決方法
這篇文章主要給大家介紹了mybatis中foreach報(bào)錯(cuò):_frch_item_0 not found的解決方法,文章通過(guò)示例代碼介紹了詳細(xì)的解決方法,對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-06-06Springboot結(jié)合Flowable實(shí)現(xiàn)工作流開(kāi)發(fā)
本文主要介紹了Springboot結(jié)合Flowable實(shí)現(xiàn)工作流開(kāi)發(fā),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01java swing實(shí)現(xiàn)簡(jiǎn)單計(jì)算器界面
這篇文章主要為大家詳細(xì)介紹了java swing實(shí)現(xiàn)簡(jiǎn)單計(jì)算器界面,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04手把手教你用Java給暗戀對(duì)象發(fā)送一份表白郵件
隨著我們學(xué)習(xí)java的深入,也漸漸發(fā)現(xiàn)了它的一些樂(lè)趣,比如發(fā)送郵件,下面這篇文章主要給大家介紹了關(guān)于如何利用Java給暗戀對(duì)象發(fā)送一份表白郵件的相關(guān)資料,需要的朋友可以參考下2021-11-11