Guava Optional類


Optional用於包含非空物件的不可變物件。 Optional物件,用於不存在值表示null。這個類有各種實用的方法,以方便程式碼來處理為可用或不可用,而不是檢查null值。

類宣告

以下是com.google.common.base.Optional<T>類的宣告:

@GwtCompatible(serializable=true)
public abstract class Optional<T>
   extends Object
      implements Serializable

類方法

S.N. 方法及說明
1 static <T> Optional<T> absent()
返回沒有包含的參考Optional的範例。
2 abstract Set<T> asSet()
返回一個不可變的單集的唯一元素所包含的範例(如果存在);否則為一個空的不可變的集合。
3 abstract boolean equals(Object object)
返回true如果物件是一個Optional範例,無論是包含參照彼此相等或兩者都不存在。
4 static <T> Optional<T> fromNullable(T nullableReference)
如果nullableReference非空,返回一個包含參照Optional範例;否則返回absent()。
5 abstract T get()
返回所包含的範例,它必須存在。
6 abstract int hashCode()
返回此範例的雜湊碼。
7 abstract boolean isPresent()
返回true,如果這支架包含一個(非空)的範例。
8 static <T> Optional<T> of(T reference)
返回包含給定的非空參照Optional範例。
9 abstract Optional<T> or(Optional<? extends T> secondChoice)
返回此Optional,如果它有一個值存在; 否則返回secondChoice。
10 abstract T or(Supplier<? extends T> supplier)
返回所包含的範例(如果存在); 否則supplier.get()。
11 abstract T or(T defaultValue)
返回所包含的範例(如果存在);否則為預設值。
12 abstract T orNull()
返回所包含的範例(如果存在);否則返回null。
13 static <T> Iterable<T> presentInstances(Iterable<? extends Optional<? extends T>> optionals)
從提供的optionals返回每個範例的存在的值,從而跳過absent()。
14 abstract String toString()
返回此範例的字串表示。
15 abstract <V> Optional<V> transform(Function<? super T,V> function)
如果範例存在,則它被轉換給定的功能;否則absent()被返回。

繼承的方法

這個類繼承了以下類的方法:

  • java.lang.Object

Optional範例:

使用所選擇的編輯器,建立下面的java程式,比如 C:/> Guava

GuavaTester.java
import com.google.common.base.Optional;

public class GuavaTester {
   public static void main(String args[]){
      GuavaTester guavaTester = new GuavaTester();

      Integer value1 =  null;
      Integer value2 =  new Integer(10);
      //Optional.fromNullable - allows passed parameter to be null.
      Optional<Integer> a = Optional.fromNullable(value1);
      //Optional.of - throws NullPointerException if passed parameter is null
      Optional<Integer> b = Optional.of(value2);		

      System.out.println(guavaTester.sum(a,b));
   }

   public Integer sum(Optional<Integer> a, Optional<Integer> b){
      //Optional.isPresent - checks the value is present or not
      System.out.println("First parameter is present: " + a.isPresent());

      System.out.println("Second parameter is present: " + b.isPresent());

      //Optional.or - returns the value if present otherwise returns
      //the default value passed.
      Integer value1 = a.or(new Integer(0));	

      //Optional.get - gets the value, value should be present
      Integer value2 = b.get();

      return value1 + value2;
   }	
}

驗證結果

使用javac編譯器編譯如下類

C:\Guava>javac GuavaTester.java

現在執行GuavaTester看到的結果

C:\Guava>java GuavaTester

看到結果。

First parameter is present: false
Second parameter is present: true
10