原文链接:Java解决if(!=null)臭名昭著的判空处理(Optional)
😝😏
话不多说,我们先来看一下下面这个代码:
/**
* 场景一:
* 获得实体对象的某个值
*/
private String getDemoEntityDeName1(DemoEntity demoEntity) {
if (demoEntity != null) {
DemoEntitySon demoEntitySon = demoEntity.getDemoEntitySon();
if (demoEntitySon != null) {
String strName = demoEntitySon.getDeName();
if (strName != null) {
return strName;
}
}
}
return null;
}
我们可以看见,为了获得,一个name,必须要进行多次空判断,否则,就存在空异常!!!
那么如何改进呢?
jdk1.8提出了Optional方法用来解决此方法:
依然是上述代码,改如何改进?
//改进写法
private String getDemoEntityDeName2(DemoEntity demoEntity) {
return Optional.ofNullable(demoEntity)
.map(DemoEntity::getDemoEntitySon)
.map(DemoEntitySon::getDeName).orElse(null);
}
接着看场景二:
/**
* 场景二:
* 判断对象或者字符是否为空,为空返回false,非空true
*/
private boolean getBoType1() {
String type = null;
if (type == null) {
return false;
} else {
return true;
}
}
我们为了获得判断是否为null,进行这样写?一点也不美观,如果代码多了,可读性极差。。。
//改进写法
private boolean getBoType2() {
String type = null;
return Optional.ofNullable(type).isPresent();
/**
* 源码:
* public boolean isPresent() {
* return value != null;
* }
*/
}
现在代码看起来比之前采用条件分支的冗长代码简洁多了。
以下扒一下,两个方法的源码,看起来也不难。
//of方法源码
private void testOf() {
//这里一定会抛出异常
DemoEntity demoEntity = null;
Optional.of(demoEntity);
/** 源码:为null直接抛空指针异常
* public static <T> T requireNonNull(T obj) {
* if (obj == null)
* throw new NullPointerException();
* return obj;
* }
*/
}
//OfNullable源码
private void testOfNullable() {
DemoEntity demoEntity = null;
Optional.ofNullable(demoEntity).orElse(null);
/** 源码:直接判空和of判断
* public static <T> Optional<T> ofNullable(T value) {
* return value == null ? empty() : of(value);
* }
*/
}
用法如上,原理用法请直接扒源码,很简单看懂。