概述
不知道你又沒有遇到過這種問題
比如我們有一個對象 customer
我們現(xiàn)在想執(zhí)行 customer.getRequirement().getType()
得到 type
但是你在代碼里肯定不能這么寫
因?yàn)?如果 getRequirement()
返回 null
碧库,那么這句代碼就拋 空指針異常了
但是層級多的時候,把每一層都拆開拣度,判空随闽,顯得很麻煩丙猬,有沒有簡便方法呢?
有洁墙,請看示例代碼
示例
Integer type = Null.of(() -> customer.getRequirement().getType(), -1);
String communityId = Null.ofString(() -> doc.getCommonProperty().getUnitCommonForVisitor().getCommunityId());
第一行有兩個參數(shù)蛆封,第二個參數(shù)是默認(rèn)值,當(dāng)前面取不到的時候碎捺,返回默認(rèn)值
第二行,方法名為 ofString
贷洲, 意思是 前面取不到的時候收厨,默認(rèn)返回空字符串
實(shí)現(xiàn)
以下是實(shí)現(xiàn)代碼,是同事實(shí)現(xiàn)的
public class Null {
private static final Logger log = LoggerFactory.getLogger(Null.class);
public static final <T> T of(Supplier<T> expr, Supplier<T> defaultValue){
try{
T result = expr.get();
if(result == null){
return defaultValue.get();
}
return result;
}catch (NullPointerException|IndexOutOfBoundsException e) {
return defaultValue.get();
}catch (Exception e) {
log.error("ObjectHelper get error.", e);
throw new RuntimeException(e);
}
}
public static final <T> T of(Supplier<T> expr, T defaultValue){
Supplier<T> defaultValues = ()-> defaultValue;
return of(expr, defaultValues);
}
public static final <T> T of(Supplier<T> expr){
Supplier<T> defaultValues = ()-> null;
return of(expr, defaultValues);
}
public static final <T> T ofString(Supplier<T> expr){
Supplier<T> defaultValues = ()-> (T)"";
return of(expr, defaultValues);
}
}