Optional类
* Optional类: 为了在程序中避免出现空指针异常而创建的。
*
* 通常的方法: ofNullable(T t): t可以为null
* orElse(T t): t为备胎
创建Optional类对象
创建Optional类对象的方式:
- Optional.of(T t) : 创建一个 Optional 实例,t必须非空;
- Optional.empty() : 创建一个空的 Optional 实例
- Optional.ofNullable(T t):t可以为nul
@Test
public void test1(){
Girl girl
= new Girl();
Optional
<Girl> optional
= Optional
.of(girl
);
System
.out
.println(optional
);
}
@Test
public void test2(){
Girl girl
= new Girl();
girl
= null
;
Optional
<Girl> optional
= Optional
.ofNullable(girl
);
System
.out
.println(optional
);
}
Optional类的使用举例
以前出现空指针的情况
以前出现空指针的情况
@Test
public void test3(){
Boy boy
= new Boy();
String girlName
= getGirlName(boy
);
System
.out
.println(girlName
);
}
public String
getGirlName(Boy boy
){
return boy
.getGirl().getName();
}
没有Optional类之前的方法优化getGirlName()
没有Optional类之前的方法优化
getGirlName()
@Test
public void test4(){
Boy boy
= new Boy();
String girlName
= getGirlName1(boy
);
System
.out
.println(girlName
);
}
public String
getGirlName1(Boy boy
){
if (boy
!= null
){
Girl girl
= new Girl();
if (girl
!= null
){
String girlName
= girl
.getName();
return girlName
;
}
}
return null
;
}
使用Optional类实现方法优化
使用Optional类实现方法优化
public String
getGirlName2(Boy boy
){
Optional
<Boy> optionalBoy
= Optional
.ofNullable(boy
);
Boy boy1
= optionalBoy
.orElse(new Boy(new Girl("花花")));
Girl girl
= boy1
.getGirl();
Optional
<Girl> girlOptional
= Optional
.ofNullable(girl
);
Girl girl1
= girlOptional
.orElse(new Girl("静香"));
return girl1
.getName();
}
@Test
public void test5(){
Boy boy
= null
;
Boy boy1
= new Boy(new Girl("红红"));
String s
= getGirlName2(boy
);
System
.out
.println(s
);
}