Guava 库设计了Optional来解决null问题
1.Optional中三个静态方法:
static <T> Optional<T> | absent()
Returns an
Optional instance with no contained reference.
|
static <T> Optional<T> | fromNullable(T nullableReference)
If
nullableReference is non-null, returns an
Optional instance containing that reference; otherwise returns
absent() .
|
static <T> Optional<T> | of(T reference) |
@Test
public void testOptional(){
Optional<Integer> possible = Optional.of(6);
Optional<Integer> absentOpt = Optional.absent();
Optional<Integer> NullableOpt = Optional.fromNullable(null);
Optional<Integer> NoNullableOpt = Optional.fromNullable(10);
if(possible.isPresent()){
System.out.println("possible isPresent:"+possible.isPresent());
System.out.println("possible value:"+possible.get());
}
if(absentOpt.isPresent()){
System.out.println("absentOpt isPresent:"+absentOpt.isPresent());
System.out.println("absentOpt value:"+absentOpt.get());
}
if(NullableOpt.isPresent()){
System.out.println("NullableOpt isPresent:"+NullableOpt.isPresent());
System.out.println("NullableOpt value:"+NullableOpt.get());
}
if(NoNullableOpt.isPresent()){
System.out.println("NoNullableOpt isPresent:"+NoNullableOpt.isPresent());
System.out.println("NoNullableOpt value:"+NoNullableOpt.get());
}
}
测试结果:
possible isPresent:true
possible value:6
NoNullableOpt isPresent:true
NoNullableOpt value:10
2.Optional中实例方法
abstract Set<T> | asSet()
|
abstract boolean | isPresent()
Returns
true if this holder contains a (non-null) instance.
|
abstract T | get()
Returns the contained instance, which must be present.
|
abstract T | or(T defaultValue)
Returns the contained instance if it is present;
defaultValue otherwise.
|
abstract T | orNull()
Returns the contained instance if it is present;
null otherwise.
|
@Test
public void testOptional2(){
Optional<Long> value = mehod();
if(value.isPresent()){
System.out.println("返回值:"+value.get());
}else{
System.out.println("返回值:"+value.or(-12L));
}
System.out.println("获得返回值 orNull: " + value.orNull());
Optional<Long> valueNoNull = methodNoNull();
if(valueNoNull.isPresent()==true){
Set<Long> set=valueNoNull.asSet();
System.out.println("获得返回值 set 的 size : " + set.size());
System.out.println("获得返回值: " + valueNoNull.get());
}else{
System.out.println("获得返回值: " + valueNoNull.or(-12L));
}
System.out.println("获得返回值 orNull: " + valueNoNull.orNull());
}
private Optional<Long> methodNoNull() {
return Optional.fromNullable(15L);
}
private Optional<Long> mehod() {
return Optional.fromNullable(null);
}
测试结果:
返回值:-12
获得返回值 orNull: null
获得返回值 set 的 size : 1
获得返回值: 15
获得返回值 orNull: 15