Optional用于包含非空對(duì)象的不可變對(duì)象。 Optional對(duì)象,用于不存在值表示null。這個(gè)類有各種實(shí)用的方法,以方便代碼來處理為可用或不可用,而不是檢查null值。
類聲明
以下是com.google.common.base.Optional<T>類的聲明:
@GwtCompatible(serializable=true)
public abstract class Optional<T>
extends Object
implements Serializable原文出自【易百教程】,商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)請(qǐng)保留原文鏈接:https://www.yiibai.com/guava/guava_optional_class.html
類方法


這個(gè)類繼承了以下類的方法: java.lang.Object
使用所選擇的編輯器,創(chuàng)建下面的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;
}
}
驗(yàn)證結(jié)果
使用javac編譯器編譯如下類
C:\Guava>javac GuavaTester.java
現(xiàn)在運(yùn)行GuavaTester看到的結(jié)果
C:\Guava>java GuavaTester
看到結(jié)果
First parameter is present: false
Second parameter is present: true
10
轉(zhuǎn)載自并發(fā)編程網(wǎng)-ifeve.com