原文鏈接: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);
* }
*/
}
用法如上,原理用法請直接扒源碼,很簡單看懂。