Optional 类
@Test public void test2(){ Girl girl = new Girl(); // girl = null; //ofNullable(T t):t可以为null Optional<Girl> optionalGirl = Optional.ofNullable(girl); System.out.println(optionalGirl); //orElse(T t1):如果单前的Optional内部封装的t是非空的,则返回内部的t. //如果内部的t是空的,则返回orElse()方法中的参数t1. Girl girl1 = optionalGirl.orElse(new Girl("赵丽颖")); System.out.println(girl1); } @Test public void test4(){ Boy boy = new Boy(); boy = null; String girlName = getGirlName1(boy); System.out.println(girlName); } //使用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(); }