Java 14 Instanceof的模式匹配

簡述

instanceof用於檢查對象引用是否爲給定Type的實例以及是否爲給定Type的實例,並返回布爾值標誌。它通過對運算符instanceOf進行模式匹配來改進Java的編程語言。模式匹配允許在系統中更清晰有效地表達邏輯,可以在對象中有條件地刪除。

Java 14 以前的使用方式

if (obj instanceof String) {
    String str = (String) obj; // need to declare and cast again the object
    .. str.contains(..) ..
}else{
     str = ....
}

Java 14 中的方式

if (!(obj instanceof String str)) {
    .. str.contains(..) .. // no need to declare str object again with casting
} else {
    .. str....
}
if (obj instanceof String str && str.length() > 5) {.. str.contains(..) ..}

if (obj instanceof String str || str.length() > 5) {.. str.contains(..) ..}

注意

instanceof僅在object不爲null時才匹配,然後僅將其分配給str。在instanceof中使用模式匹配應減少Java程序中顯式強制轉換的總數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章