概述
不知道你又没有遇到过这种问题
比如我们有一个对象 customer
我们现在想执行 customer.getRequirement().getType()
得到 type
但是你在代码里肯定不能这么写
因为 如果 getRequirement()
返回 null
,那么这句代码就抛 空指针异常了
但是层级多的时候,把每一层都拆开,判空,显得很麻烦,有没有简便方法呢?
有,请看示例代码
示例
Integer type = Null.of(() -> customer.getRequirement().getType(), -1);
String communityId = Null.ofString(() -> doc.getCommonProperty().getUnitCommonForVisitor().getCommunityId());
第一行有两个参数,第二个参数是默认值,当前面取不到的时候,返回默认值
第二行,方法名为 ofString
, 意思是 前面取不到的时候,默认返回空字符串
实现
以下是实现代码,是同事实现的
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);
}
}
网友评论