具体操作
public class Girl {
private String name;
public Girl() {
}
public Girl(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Girl{" +
"name='" + name + '\'' +
'}';
}
}
public class Boy {
private Girl girl;
public Boy(){
}
public Boy(Girl girl){
this.girl = girl;
}
public Girl getGirl() {
return girl;
}
public void setGirl(Girl girl) {
this.girl = girl;
}
}
创建Optional类对象的方法
@Test
public void test1(){
Girl girl = new Girl();
//保证t是非空的
Optional<Girl> optionalGirl = Optional.of(girl);
}
@Test
public void test2(){
Girl girl = new Girl();
girl = null;
//t可以为null
Optional<Girl> optionalGirl = Optional.ofNullable(girl);
System.out.println(optionalGirl);
}
以前写代码会出现空指针
public String getGirlName(Boy boy){
return boy.getGirl().getName();
}
@Test
public void test3(){
Boy boy = new Boy();
String girlName = getGirlName(boy);
System.out.println(girlName);
}
优化后的代码
//优化以后的getGirlName();
public String getGirlName1(Boy boy){
if (boy != null){
Girl girl = boy.getGirl();
if (girl != null){
return girl.getName();
}
}
return null;
}
@Test
public void test4(){
Boy boy = new Boy();
String girlName = getGirlName1(boy);
System.out.println(girlName);
}
使用Optional代码进行优化
//Optional优化以后的getGirlName();
public String getGirlName2(Boy boy){
Optional<Boy> optionalBoy = Optional.ofNullable(boy);
//boy1一定非空
Boy boy1 = optionalBoy.orElse(new Boy(new Girl("贾斯汀")));
Girl girl = boy1.getGirl();
Optional<Girl> girlOptional = Optional.ofNullable(girl);
//girl1一定非空
Girl girl1 = girlOptional.orElse(new Girl("虎牙"));
return girl1.getName();
}
@Test
public void test5(){
Boy boy = null;
String girlName = getGirlName2(boy);
System.out.println(girlName);
}