package com.atguigu.java3;
import org.junit.Test;
import java.util.Optional;
/**
* Optional类:为了在程序中避免空指针异常而出现的
* 常用方法:ofNullable(T t)
* orElse(T t)
* @author
* @create 2022-05-09-9:53
*/
public class OptionalTest {
/*
Optional.of(T t):创建一个Optional实例,t必须非空
Optional.empty():创建一个空的Optional实例
Optional.ofNullable(T t):t可以为null
*/
@Test
public void test1(){
Girl girl = new Girl();
girl=null;
// Optional<Girl> optionalGirl = Optional.of(girl);//of(T t)必须保证t是非空的
Optional<Girl> girl1 = Optional.ofNullable(girl);//ofNullable(T t):t可以为null
System.out.println(girl1);//Optional.empty
//orElse(T t):如果当前的Optional内部封装的t是非空的,则返回内部的t,如果内部的t是空的,则返回
//orElse()方法中的t.
Girl girl2 = girl1.orElse(new Girl("小红"));
System.out.println(girl2);
}
public String getGirlName(Boy boy){
return boy.getGirl().getName();
}
@Test
public void test2(){
Boy boy = new Boy();
String girlName = getGirlName(boy);
System.out.println(girlName);
}
//优化以后的getGirlName()
public String getGirlName1(Boy boy){
if (boy!=null){
if (boy.getGirl()!=null){
return boy.getGirl().getName();
}
}
return null;
}
//使用Optional类的getGirlName()
public String getGirlName2(Boy boy) {
Optional<Boy> boyOptional = Optional.ofNullable(boy);
//此时boy1一定非空
Boy boy1 = boyOptional.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 test3(){
Boy boy=null;
boy=new Boy();
String girlName = getGirlName2(boy);
System.out.println(girlName);
}
}
package com.atguigu.java3;
/**
* @author
* @create 2022-05-09-9:50
*/
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;
}
@Override
public String toString() {
return "Boy{" +
"girl=" + girl +
'}';
}
}
package com.atguigu.java3;
/**
* @author
* @create 2022-05-09-9:51
*/
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 + '\'' +
'}';
}
}
?
?
|