public String getGirlName(Boy boy){ return boy.getGirl().getName(); }
@Test publicvoidtest2(){ Boy boy = new Boy(); boy = null; // java.lang.NullPointerException String girlName = getGirlName(boy); System.out.println(girlName);
}
/** * 优化以后的getGirlName() * * @param boy * @return */ public String getGirlName1(Boy boy){ if (boy != null) { Girl girl = boy.getGirl(); if (girl != null) { return girl.getName(); } } returnnull;
}
@Test publicvoidtest3(){ Boy boy = new Boy(); boy = null; String girlName = getGirlName1(boy); // null System.out.println(girlName);
}
/** * 使用Optional类的getGirlName(): * @param boy * @return */ public String getGirlName2(Boy boy){
@Test publicvoidtest4(){ Boy boy = null; boy = new Boy(); // boy = new Boy(new Girl("苍老师")); String girlName = getGirlName2(boy); System.out.println(girlName);