简介
一直一以来 java 对 null 处理都是挺麻烦和痛苦的,为了防止 NullPointerException 我们需要做很多 null 检查。
例如:root.getSecond().getThird().getValue()
,为了从 root 获取到 third.value 的值,代码上需要做很多 null 检查
if(root != null && root.getSecond() != null && root.getSecond().getThird() != null){
return root.getSecond().getThird().getValue();
}
为了简化这些繁琐的操作所以利用 lamdba 表达式写了一个工具类
点击查看工具类代码
使用方法
// 获取值,如果有任何一级为 null 则返回 null
Integer value = NullPointUtil.get(() -> root.getSecond().getThird().getValue());
// 获取值,如果有任何一级为 null 则返回 默认值
Integer value = NullPointUtil.get(() -> root.getSecond().getThird().getValue(), defalutValue);
// 建议使用该方式
Optional<Integer> optional = NullPointUtil.getOptional(() -> root.getSecond().getThird().getValue());
// 判断是否能获取到值
boolean isNull = NullPointUtil.isNull(() -> root.getSecond().getThird().getValue());
boolean nonNull= NullPointUtil.nonNull(() -> root.getSecond().getThird().getValue());
// 判断值是否等于10
if (NullPointUtil.test(() -> root.getSecond().getThird().getValue() == 10)){
}
// 相当于下面的判断
if (root != null && root.getSecond() != null
&& root.getSecond().getThird() != null
&& root.getSecond().getThird().getValue() != null
&& root.getSecond().getThird().getValue() == 10){
}
// 判断值是否不等于10
if (NullPointUtil.testOrNull(() -> root.getSecond().getThird().getValue() != 10)){
}
// 相当于下面的判断
if (root == null || root.getSecond() == null
|| root.getSecond().getThird() == null
|| root.getSecond().getThird().getValue() == null
|| root.getSecond().getThird().getValue() != 10){
}
// 判断获取的两个值是否相等
if (NullPointUtil.equals(() -> root1.getSecond().getThird().getValue(),
() -> root2.getSecond().getThird().getValue())){
}