java~Optional語法糖

一、簡介
Optional類是Java8爲了解決null值判斷問題,借鑑google guava類庫的Optional類而引入的一個同名Optional類,使用Optional類可以避免顯式的null值判斷(null的防禦性檢查),避免null導致的NPE(NullPointerException)。

  • 我們來看一段代碼:
    public static String getGender(Student student)
    {
        if(null == student)
        {
            return "Unkown";
        }
        return student.getGender();
        
    }

這是一個獲取學生性別的方法,方法入參爲一個Student對象,爲了防止student對象爲null, 做了防禦性檢查:如果值爲null,返回"Unkown"。

  • 再看使用Optional優化後的方法:
    public static String getGender(Student student)
    {
       return Optional.ofNullable(student).map(u -> u.getGender()).orElse("Unkown");       
    }

可以看到,Optional類結合lambda表達式的使用能夠讓開發出的代碼更簡潔和優雅。

二、Optional對象的創建

我們看下Optional類的部分源碼:

    private static final Optional<?> EMPTY = new Optional<>();

    private final T value;

    private Optional() {
        this.value = null;
    }

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

    private Optional(T value) {
        this.value = Objects.requireNonNull(value);
    }

    public static <T> Optional<T> of(T value) {
        return new Optional<>(value);
    }

    public static <T> Optional<T> ofNullable(T value) {
        return value == null ? empty() : of(value);
    }

可以看出,Optional類的兩個構造方法都是private型的,因此類外部不能顯示的使用new Optional()的方式來創建Optional對象,但是Optional類提供了三個靜態方法empty()、of(T value)、ofNullable(T value)來創建Optinal對象,示例如下:

  1. 創建一個包裝對象值爲空的Optional對象
    Optional optStr = Optional.empty();
  2. 創建包裝對象值非空的Optional對象
    Optional optStr1 = Optional.of("optional");
  3. 創建包裝對象值允許爲空的Optional對象
    Optional optStr2 = Optional.ofNullable(null);

三、Optional 類典型接口的使用

下面以一些典型場景爲例,列出Optional API常用接口的用法,並附上相應代碼。

  • 3.1 get()方法
    簡單看下get()方法的源碼:
    public T get() {
        if (value == null) {
            throw new NoSuchElementException("No value present");
        }
        return value;
    }

可以看到,get()方法主要用於返回包裝對象的實際值,但是如果包裝對象值爲null,會拋出NoSuchElementException異常。

  • 3.2 isPresent()方法
    isPresent()方法的源碼:
    public boolean isPresent() {
        return value != null;
    }

可以看到,isPresent()方法用於判斷包裝對象的值是否非空。下面我們來看一段糟糕的代碼:

    public static String getGender(Student student)
    {
        Optional<Student> stuOpt =  Optional.ofNullable(student);
        if(stuOpt.isPresent())
        {
            return stuOpt.get().getGender();
        }
        
        return "Unkown";
    }

這段代碼實現的是第一章(簡介)中的邏輯,但是這種用法不但沒有減少null的防禦性檢查,而且增加了Optional包裝的過程,違背了Optional設計的初衷,因此開發中要避免這種糟糕的使用~

  • 3.3 ifPresent()方法
    ifPresent()方法的源碼:
    public void ifPresent(Consumer<? super T> consumer) {
        if (value != null)
            consumer.accept(value);
    }

ifPresent()方法接受一個Consumer對象(消費函數),如果包裝對象的值非空,運行Consumer對象的accept()方法。示例如下:

    public static void printName(Student student)
    {
        Optional.ofNullable(student).ifPresent(u ->  System.out.println("The student name is : " + u.getName()));
    }

上述示例用於打印學生姓名,由於ifPresent()方法內部做了null值檢查,調用前無需擔心NPE問題。
3.4  filter()方法
     filter()方法的源碼:
    public Optional<T> filter(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate);
        if (!isPresent())
            return this;
        else
            return predicate.test(value) ? this : empty();
    }

filter()方法接受參數爲Predicate對象,用於對Optional對象進行過濾,如果符合Predicate的條件,返回Optional對象本身,否則返回一個空的Optional對象。舉例如下:

    public static void filterAge(Student student)
    {
        Optional.ofNullable(student).filter( u -> u.getAge() > 18).ifPresent(u ->  System.out.println("The student age is more than 18."));
    }

上述示例中,實現了年齡大於18的學生的篩選。

  • 3.5 map()方法
    map()方法的源碼:
  public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
        Objects.requireNonNull(mapper);
        if (!isPresent())
            return empty();
        else {
            return Optional.ofNullable(mapper.apply(value));
        }
    }

map()方法的參數爲Function(函數式接口)對象,map()方法將Optional中的包裝對象用Function函數進行運算,幷包裝成新的Optional對象(包裝對象的類型可能改變)。舉例如下:

    public static Optional<Integer> getAge(Student student)
    {
        return Optional.ofNullable(student).map(u -> u.getAge()); 
    }

上述代碼中,先用ofNullable()方法構造一個Optional對象,然後用map()計算學生的年齡,返回Optional對象(如果student爲null, 返回map()方法返回一個空的Optinal對象)。

  • 3.6 flatMap()方法
    flatMap()方法的源碼:
  public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
        Objects.requireNonNull(mapper);
        if (!isPresent())
            return empty();
        else {
            return Objects.requireNonNull(mapper.apply(value));
        }
    }

跟map()方法不同的是,入參Function函數的返回值類型爲Optional類型,而不是U類型,這樣flatMap()能將一個二維的Optional對象映射成一個一維的對象。以3.5中示例功能爲例,進行faltMap()改寫如下:

 public static Optional<Integer> getAge(Student student)
    {
        return Optional.ofNullable(student).flatMap(u -> Optional.ofNullable(u.getAge())); 
    }
  • 3.7 orElse()方法
    orElse()方法的源碼:
    public T orElse(T other) {
        return value != null ? value : other;
    }

orElse()方法功能比較簡單,即如果包裝對象值非空,返回包裝對象值,否則返回入參other的值(默認值)。如第一章(簡介)中提到的代碼:

    public static String getGender(Student student)
    {
       return Optional.ofNullable(student).map(u -> u.getGender()).orElse("Unkown");    
    }

3.7  orElseGet()方法
     orElseGet()方法的源碼:
    public T orElseGet(Supplier<? extends T> other) {
        return value != null ? value : other.get();
    }

orElseGet()方法與orElse()方法類似,區別在於orElseGet()方法的入參爲一個Supplier對象(供應者),用Supplier對象的get()方法的返回值作爲默認值。如:

   public static String getGender(Student student)
    {
        return Optional.ofNullable(student).map(u -> u.getGender()).orElseGet(() -> "Unkown");      
    }
  • 3.8 orElseThrow()方法
    orElseThrow()方法的源碼:
    public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
        if (value != null) {
            return value;
        } else {
            throw exceptionSupplier.get();
        }
    }

orElseThrow()方法其實與orElseGet()方法非常相似了,入參都是Supplier對象,只不過orElseThrow()的Supplier對象必須返回一個Throwable異常,並在orElseThrow()中將異常拋出:

    public static String getGender1(Student student)
    {
        return Optional.ofNullable(student).map(u -> u.getGender()).orElseThrow(() -> new RuntimeException("Unkown"));      
    }

orElseThrow()方法適用於包裝對象值爲空時需要拋出特定異常的場景。

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