Guava Optional类
Optional用于包含非空对象的不可变对象。 Optional对象,用于不存在值表示null。这个类有各种实用的方法,以方便代码来处理为可用或不可用,而不是检查null值。
类声明
以下是com.google.common.base.Optional 类的声明:
@GwtCompatible(serializable=true) public abstract class Optional<T> extends Object implements Serializable
类方法
继承的方法
这个类继承了以下类的方法: 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()); //http://www.wityx.com/post/1245_1_1.html 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