Optional用于包含非空對象的不可變對象。 Optional對象,用于不存在值表示null。這個類有各種實用的方法,以方便代碼來處理為可用或不可用,而不是檢查null值。
類聲明
以下是com.google.common.base.Optional<T>類的聲明:
@GwtCompatible(serializable=true)
public abstract class Optional<T>
extends Object
implements Serializable原文出自【易百教程】,商業轉載請聯系作者獲得授權,非商業請保留原文鏈接:https://www.yiibai.com/guava/guava_optional_class.html
類方法
這個類繼承了以下類的方法: java.lang.Object
使用所選擇的編輯器,創建下面的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
轉載自并發編程網-ifeve.com