详细内容请参考Google Guava官方教程(中文版)
Optional
创建Optional实例(以下都是静态方法)
方法声明 | 描述 |
---|
Optional.of(T) | 创建指定引用的Optional实例,若引用为null则快速失败 |
Optional.absent() | 创建引用缺失的Optional实例 |
Optional.fromNullable(T) | 创建指定引用的Optional实例,若引用为null则表示缺失 |
用Optional实例查询引用(以下都是非静态方法)
方法 | 使用说明 |
---|
boolean isPresent() | 如果Optional包含非null的引用(引用存在),返回true |
T get() | 返回Optional所包含的引用,若引用缺失,则抛出java.lang.IllegalStateException |
T or(T) | 返回Optional所包含的引用,若引用缺失,返回null |
T orNull() | 创建指定引用的Optional实例,若引用为null则表示缺失 |
Set asSet() | 返回Optional所包含引用的单例不可变集,如果引用存在,返回一个只有单一元素的集合,如果引用缺失,返回一个空集合。 |
代码
package com.test.guava.BasicUtilities;
import com.google.common.base.Optional;
public class OptionalTest {
public static void main(String[] args) {
Optional<String> possible = Optional.of("");
System.out.println(possible.isPresent());
Optional<Integer> possible1 = Optional.of(5);
System.out.println(possible1.isPresent());
Optional<Integer> possible2 = null;
try {
Optional.of(null);
} catch (Exception e) {
System.out.println("possible2包含null");
}
Optional<Integer> possible3 = Optional.fromNullable(5);
System.out.println(possible3.isPresent());
System.out.println(possible3.get());
Optional<Integer> possible4 = Optional.fromNullable(null);
System.out.println(possible4.isPresent());
try {
possible4.get();
} catch (Exception e) {
System.out.println("possible4包含null");
}
Optional<Integer> possible5 = Optional.fromNullable(5);
System.out.println(possible5.or(3));
Optional<Integer> possible6 = Optional.fromNullable(null);
System.out.println(possible6.or(3));
Optional<Integer> possible7 = Optional.absent();
System.out.println(possible7.isPresent());
Optional<Integer> possible8 = Optional.fromNullable(5);
System.out.println(possible8.orNull());
Optional<Integer> possible9 = Optional.fromNullable(null);
System.out.println(possible9.orNull());
Optional<Integer> possible10 = Optional.absent();
System.out.println(possible10.orNull());
Optional<Integer> possible11 = Optional.fromNullable(5);
System.out.println(possible11.asSet());
Optional<Integer> possible12 = Optional.fromNullable(null);
System.out.println(possible12.asSet());
}
}
运行结果
true
true
possible2包含null
true
5
false
possible4包含null
5
3
false
5
null
null
[5]
[]
Process finished with exit code 0