New feature of JDK 14: instanceof pattern matching
New feature of JDK 14: instanceof pattern matching
Jdk14 was officially released in March 2020. Unfortunately, the formal feature only includes the latest switch expressions, while records, patterns and text blocks are still preview features.
This article is about pattern matching of instanceof, a preview feature of jdk14. In other words, pattern matching can be used in instanceof.
How to understand?
Let's start with an example of using instanceof in the historical version.
If we are the zookeeper, there are two kinds of animals in the zoo: girrafe and hippo.
@Data
public class Girraffe {
private String name;
}
@Data
public class Hippo {
private String name;
}
For simplicity, we define a name attribute for both of the above animals.
Next, we need to manage two kinds of animals, introduce an animal, and judge whether the animal is one of the above two animals. According to the traditional method, we should do this:
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("对不起,该动物不是地球上的生物!");
}
In the above code, if instanceof is confirmed successfully, we also need to convert the object to call the methods in the corresponding object.
With JDK 14, everything becomes easier. Let's look at the pattern matching of the latest JDK 14:
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("对不起,该动物不是地球上的生物!");
}
Note the usage of instanceof. Through the pattern matching of instanceof, there is no need for secondary conversion. Just use it directly. Moreover, the object of pattern matching is also limited to the scope, which will be more secure.
Examples of this article https://github.com/ddean2009/learn-java-base-9-to-20