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
上一篇:
Guava環境設置
下一篇:
Guava Preconditions類
