Java8新特性之Optional類

一 概述

Java8中引入了很多新特性,其中Optional類就是一個很重要的特性,它主要功能是解決NPE(NullPointerException)問題。其實Optional是一個包含有可選值的包裝類,即Optional類既可以含有對象值也可以爲NULL,這樣可以減少我們在實際編碼中對空值的判斷。此外,Optional類也是Java8函數式編程的一大體現。

二 Optional類的實例之Empty()

 

如代碼測試結果所示,這樣會拋出SuchElementException的異常。

三 Opitonal類之of()&ofNullable()

1 of()

  

2 ofNullable()

  

由代碼可知,當對象爲NULL時,使用of()方法是會返回NullPointerException異常。而ofNullable()方法就不會,具體原因見源碼。

Objects.class
public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }

Optional.class
public static<T> Optional<T> empty() {
        @SuppressWarnings("unchecked")
        Optional<T> t = (Optional<T>) EMPTY;
        return t;
    }

    /**
     * Constructs an instance with the value present.
     *
     * @param value the non-null value to be present
     * @throws NullPointerException if value is null
     */
    private Optional(T value) {
        this.value = Objects.requireNonNull(value);
    }

    /**
     * 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);
    }

    /**
     * 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);
    }

四 Optional類之get()

 

get()方法在對象爲null時,會拋出NoSuchElementException,所以我們需要先進行空值檢查。

/**
     * If a value is present in this {@code Optional}, returns the value,
     * otherwise throws {@code NoSuchElementException}.
     *
     * @return the non-null value held by this {@code Optional}
     * @throws NoSuchElementException if there is no value present
     *
     * @see Optional#isPresent()
     */
    public T get() {
        if (value == null) {
            throw new NoSuchElementException("No value present");
        }
        return value;
    }

使用isPresent()方法進行空值檢查

還有另一個ifPresent()方法,源碼如下

    Optional.class
    /**
     * If a value is present, invoke the specified consumer with the value,
     * otherwise do nothing.
     *
     * @param consumer block to be executed if a value is present
     * @throws NullPointerException if value is present and {@code consumer} is
     * null
     */
    //Consumer是函數式接口,所以可以使用Lambda表達式來做方法的參數
    public void ifPresent(Consumer<? super T> consumer) {
        if (value != null)
            consumer.accept(value);
    }


    @FunctionalInterface
    public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    //接口中的方法默認時public abstract關鍵字修飾
    void accept(T t);
    }

  

返回默認值

Optional 類提供了 API 用以返回對象值,或者在對象爲空的時候返回默認值。

這裏你可以使用的第一個方法是 orElse(),它的工作方式非常直接,如果有值則返回該值,否則返回傳遞給它的參數值:

@Test
public void whenEmptyValue_thenReturnDefault() {
    User user = null;
    User user2 = new User("[email protected]", "1234");
    User result = Optional.ofNullable(user).orElse(user2);

    assertEquals(user2.getEmail(), result.getEmail());
}

這裏 user 對象是空的,所以返回了作爲默認值的 user2。如果對象的初始值不是 null,那麼默認值會被忽略:

@Test
public void whenValueNotNull_thenIgnoreDefault() {
    User user = new User("[email protected]","1234");
    User user2 = new User("[email protected]", "1234");
    User result = Optional.ofNullable(user).orElse(user2);

    assertEquals("[email protected]", result.getEmail());
}

第二個同類型的 API 是 orElseGet() —— 其行爲略有不同。這個方法會在有值的時候返回值,如果沒有值,它會執行作爲參數傳入的 Supplier(供應者) 函數式接口,並將返回其執行結果:

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

 /**
     * Return the value if present, otherwise invoke {@code other} and return
     * the result of that invocation.
     *
     * @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();
    }

//Supplier爲函數式接口故可以使用Lambda表達式
User result = Optional.ofNullable(user).orElseGet( () -> user2);

orElse() 和 orElseGet() 的不同之處

乍一看,這兩種方法似乎起着同樣的作用。然而事實並非如此。我們創建一些示例來突出二者行爲上的異同。

我們先來看看對象爲空時他們的行爲:

@Test
public void givenEmptyValue_whenCompare_thenOk() {
    User user = null
    logger.debug("Using orElse");
    User result = Optional.ofNullable(user).orElse(createNewUser());
    logger.debug("Using orElseGet");
    User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());
}

private User createNewUser() {
    logger.debug("Creating New User");
    return new User("[email protected]", "1234");
}

上面的代碼中,兩種方法都調用了 createNewUser() 方法,這個方法會記錄一個消息並返回 User 對象。

代碼輸出如下:

Using orElse
Creating New User
Using orElseGet
Creating New User

由此可見,當對象爲空而返回默認對象時,行爲並無差異,我們接下來看一個類似的示例,但這裏 Optional  不爲空:

@Test
public void givenPresentValue_whenCompare_thenOk() {
    User user = new User("[email protected]", "1234");
    logger.info("Using orElse");
    User result = Optional.ofNullable(user).orElse(createNewUser());
    logger.info("Using orElseGet");
    User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());
}

這次的輸出:

Using orElse
Creating New User
Using orElseGet

這個示例中,兩個 Optional  對象都包含非空值,兩個方法都會返回對應的非空值。不過,orElse() 方法仍然創建了 User 對象。與之相反,orElseGet() 方法不創建 User 對象。在執行較密集的調用時,比如調用 Web 服務或數據查詢,這個差異會對性能產生重大影響

返回異常

除了 orElse() 和 orElseGet() 方法,Optional 還定義了 orElseThrow() API —— 它會在對象爲空的時候拋出異常,而不是返回備選的值:

@Test(expected = IllegalArgumentException.class)
public void whenThrowException_thenOk() {
    User result = Optional.ofNullable(user)
      .orElseThrow( () -> new IllegalArgumentException());
}

這裏,如果 user 值爲 null,會拋出 IllegalArgumentException。這個方法讓我們有更豐富的語義,可以決定拋出什麼樣的異常,而不總是拋出 NullPointerException。現在我們已經很好地理解了如何使用 Optional,我們來看看其它可以對 Optional 值進行轉換和過濾的方法。

轉換值

有很多種方法可以轉換 Optional  的值。我們從 map() 和 flatMap() 方法開始。先來看一個使用 map() API 的例子:

@Test
public void whenMap_thenOk() {
    User user = new User("[email protected]", "1234");
    String email = Optional.ofNullable(user)
      .map(u -> u.getEmail()).orElse("[email protected]");

    assertEquals(email, user.getEmail());
}

map() 對值應用(調用)作爲參數的函數,然後將返回的值包裝在 Optional 中。這就使對返回值進行鏈試調用的操作成爲可能 —— 這裏的下一環就是 orElse()。相比這下,flatMap() 也需要函數作爲參數,並對值調用這個函數,然後直接返回結果。下面的操作中,我們給 User 類添加了一個方法,用來返回 Optional:

public class User {    
    private String position;

    public Optional<String> getPosition() {
        return Optional.ofNullable(position);
    }

    //...
}

既然 getter 方法返回 String 值的 Optional,你可以在對 User 的 Optional 對象調用 flatMap() 時,用它作爲參數。其返回的值是解除包裝的 String 值:

@Test
public void whenFlatMap_thenOk() {
    User user = new User("[email protected]", "1234");
    user.setPosition("Developer");
    String position = Optional.ofNullable(user)
      .flatMap(u -> u.getPosition()).orElse("default");

    assertEquals(position, user.getPosition().get());
}

過濾值

除了轉換值之外,Optional  類也提供了按條件“過濾”值的方法。filter() 接受一個 Predicate 參數,返回測試結果爲 true 的值。如果測試結果爲 false,會返回一個空的 Optional。來看一個根據基本的電子郵箱驗證來決定接受或拒絕 User(用戶) 的示例:

@Test
public void whenFilter_thenOk() {
    User user = new User("[email protected]", "1234");
    Optional<User> result = Optional.ofNullable(user)
      .filter(u -> u.getEmail() != null && u.getEmail().contains("@"));

    assertTrue(result.isPresent());
}

如果通過過濾器測試,result 對象會包含非空值。

Optional 類的鏈式方法

爲了更充分的使用 Optional,你可以鏈接組合其大部分方法,因爲它們都返回相同類似的對象。我們使用 Optional  重寫最早介紹的示例。首先,重構類,使其 getter 方法返回 Optional 引用:

public class User {
    private Address address;

    public Optional<Address> getAddress() {
        return Optional.ofNullable(address);
    }

    // ...
}
public class Address {
    private Country country;

    public Optional<Country> getCountry() {
        return Optional.ofNullable(country);
    }

    // ...
}

上面的嵌套結構可以用下面的圖來表示:

optional nested

現在可以刪除 null 檢查,替換爲 Optional 的方法:

@Test
public void whenChaining_thenOk() {
    User user = new User("[email protected]", "1234");

    String result = Optional.ofNullable(user)
      .flatMap(u -> u.getAddress())
      .flatMap(a -> a.getCountry())
      .map(c -> c.getIsocode())
      .orElse("default");

    assertEquals(result, "default");
}

上面的代碼可以通過方法引用進一步縮減:

String result = Optional.ofNullable(user)
  .flatMap(User::getAddress)
  .flatMap(Address::getCountry)
  .map(Country::getIsocode)
  .orElse("default");

結果現在的代碼看起來比之前採用條件分支的冗長代碼簡潔多了。

Java 9 增強

我們介紹了 Java 8 的特性,Java 9 爲 Optional 類添加了三個方法:or()、ifPresentOrElse() 和 stream()。or() 方法與 orElse() 和 orElseGet() 類似,它們都在對象爲空的時候提供了替代情況。or() 的返回值是由 Supplier 參數產生的另一個 Optional 對象。如果對象包含值,則 Lambda 表達式不會執行:

@Test
public void whenEmptyOptional_thenGetValueFromOr() {
    User result = Optional.ofNullable(user)
      .or( () -> Optional.of(new User("default","1234"))).get();

    assertEquals(result.getEmail(), "default");
}

上面的示例中,如果 user 變量是 null,它會返回一個 Optional,它所包含的 User 對象,其電子郵件爲 “default”。

ifPresentOrElse() 方法需要兩個參數:一個 Consumer 和一個 Runnable。如果對象包含值,會執行 Consumer 的動作,否則運行 Runnable。

如果你想在有值的時候執行某個動作,或者只是跟蹤是否定義了某個值,那麼這個方法非常有用:

Optional.ofNullable(user).ifPresentOrElse( u -> logger.info("User is:" + u.getEmail()),
  () -> logger.info("User not found"));

最後介紹的是新的 stream() 方法,它通過把實例轉換爲 Stream 對象,讓你從廣大的 Stream API 中受益。如果沒有值,它會得到空的 Stream;有值的情況下,Stream 則會包含單一值。我們來看一個把 Optional 處理成 Stream 的例子:

@Test
public void whenGetStream_thenOk() {
    User user = new User("[email protected]", "1234");
    List<String> emails = Optional.ofNullable(user)
      .stream()
      .filter(u -> u.getEmail() != null && u.getEmail().contains("@"))
      .map( u -> u.getEmail())
      .collect(Collectors.toList());

    assertTrue(emails.size() == 1);
    assertEquals(emails.get(0), user.getEmail());
}

這裏對 Stream 的使用帶來了其 filter()、map() 和 collect() 接口,以獲取 List。

Optional  應該怎樣用?

在使用 Optional 的時候需要考慮一些事情,以決定什麼時候怎樣使用它。

重要的一點是 Optional 不是 Serializable。因此,它不應該用作類的字段。

如果你需要序列化的對象包含 Optional 值,Jackson 庫支持把 Optional 當作普通對象。也就是說,Jackson 會把空對象看作 null,而有值的對象則把其值看作對應域的值。這個功能在 jackson-modules-java8 項目中。

它在另一種情況下也並不怎麼有用,就是在將其類型用作方法或構建方法的參數時。這樣做會讓代碼變得複雜,完全沒有必要:

User user = new User("[email protected]", "1234", Optional.empty());

使用重載方法來處理非要的參數要容易得多。Optional 主要用作返回類型。在獲取到這個類型的實例後,如果它有值,你可以取得這個值,否則可以進行一些替代行爲。Optional 類有一個非常有用的用例,就是將其與流或其它返回 Optional 的方法結合,以構建流暢的API

我們來看一個示例,使用 Stream 返回 Optional 對象的 findFirst() 方法:

@Test
public void whenEmptyStream_thenReturnDefaultOptional() {
    List<User> users = new ArrayList<>();
    User user = users.stream().findFirst().orElse(new User("default", "1234"));

    assertEquals(user.getEmail(), "default");
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章