Java 16 (JEP 394: Pattern Matching for instanceof)
Java 16 is released. Let’s take a look at some new features for software engineers.
Today let’s try to understand how an improved instance of the operator can help us write more clear and fluent code.
Pattern matching in the JDK 16 will improve live developers who need to work with libraries that provide an Object.class instance as a return value.
Before Java 16, you needed to write code like this to prevent ClassCastException in runtime:
if (<some object instance> instance of String) {
stringProcessingService.proces((String) <some object instance>);
}
This code looks like little bit bulky;
Now with JDK 16, we can use pattern matching in our code:
if (<some object instance> instanceof String str) {
stringProcessingService.proces(str);
}
This code looks more fluent and clear.
Here is a small example how “real code” will look like:
public static void main(String[] args) {
var list = new ArrayList<>();
list.add("Hello world!");
//Without pattern matching
if (list.get(0) instanceof String) {
System.out.println("Value is a String. Length: " + ((String) list.get(0)).length());
}
//With pattern matching
if (list.get(0) instanceof String value) {
System.out.println("Value is a String. Length: " + value.length());
}
}