JDK 14的新特性:instanceof模式匹配

JDK 14的新特性:instanceof模式匹配java

JDK14在2020年的3月正式發佈了。惋惜的是正式特性只包含了最新的Switch表達式,而Records,patterns,text blocks仍然是預覽特性。git

本文要講的就是JDK14的一個預覽特性instanceof的pattern matching。 也就是說在instanceof中能夠使用模式匹配了。github

怎麼理解呢?安全

咱們先舉個歷史版本中使用instanceof的例子。code

假如咱們是動物園的管理員,動物園裏面有Girraffe和Hippo兩種動物。對象

@Data
public class Girraffe {
    private String name;
}
@Data
public class Hippo {
    private String name;
}

爲了簡單起見,上面兩種動物咱們都之定義一個name屬性。ip

接下來咱們要對兩種動物進行管理,傳入一個動物,判斷一下這個動物是否是上面兩種動物之一,按照傳統的辦法,咱們應該這樣作:作用域

public void testZooOld(Object animal){
        if(animal instanceof Girraffe){
            Girraffe girraffe = (Girraffe) animal;
            log.info("girraffe name is {}",girraffe.getName());
        }else if(animal instanceof Hippo){
            Hippo hippo = (Hippo) animal;
            log.info("hippo name is {}",hippo.getName());
        }
        throw new IllegalArgumentException("對不起,該動物不是地球上的生物!");
    }

上面的代碼中, 若是instanceof確認成功,咱們還須要將對象進行轉換,才能調用相應對象中的方法。get

有了JDK 14,一切都變得容易了,咱們看下最新的JDK 14的模式匹配怎麼作:it

public void testZooNew(Object animal){
        if(animal instanceof Girraffe girraffe){
            log.info("name is {}",girraffe.getName());
        }else if(animal instanceof Hippo hippo){
            log.info("name is {}",hippo.getName());
        }
        throw new IllegalArgumentException("對不起,該動物不是地球上的生物!");
    }

注意instanceof的用法,經過instanceof的模式匹配,就不須要二次轉換了。直接使用就能夠了。而且模式匹配的對象還被限定了做用域範圍,會更加安全。

注意,若是你使用的最新版的IntelliJ IDEA 2020.1版本的話,語言編譯版本必定要選擇14(Preview),由於這個功能是preview的。

本文的例子[https://github.com/ddean2009/...
](https://github.com/ddean2009/...

歡迎關注個人公衆號:程序那些事,更多精彩等着您!

更多內容請訪問 www.flydean.com

相關文章
相關標籤/搜索