# Use Pattern Matching for Instanceof

# Description

This rule replaces instanceof expressions by Pattern Matching for instanceof (opens new window) introduced in Java 16.

It is very common for Java programs to contain logic that combines type checking using instanceof with explicit type casting. Naturally, an instanceof expression is followed by a local variable declaration initialized with a casting expression. Pattern Matching for instanceof combines these three steps (i.e., type checking, variable declaration, and type casting) into a single step, thus reducing boilerplate code and eliminating sources of errors.

Requirements

  • Java 16

# Benefits

Removes code clutter. Improves readability.

# Tags

# Code Changes

# Pattern Matching in If Statement

Pre

if(o instanceof String) {
    String value = (String)o;		
    showValue(value);
}

Post

if(o instanceof String value) {
    showValue(value);
}

# Pattern Matching in If-Then-Else Statement

Pre

if (!(o instanceof String)) {
    dontShowValue();
} else {
    String value = (String) o;
    showValue(value);
}

Post

if (!(o instanceof String value)) {
    dontShowValue();
} else {
    showValue(value);
}

# Pattern Matching with Return Statement

Pre

if (!(o instanceof String)) {
    dontShowValue();
    return false;
}
String value = (String)o;
showValue(value);
return "Olympics 2020".equals(value);

Post

if (!(o instanceof String value)) {
    dontShowValue();
    return false;
}
showValue(value);
return "Olympics 2020".equals(value);

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

Property Value
Rule ID UsePatternMatchingForInstanceof
First seen in jSparrow version 4.2.0
Minimum Java version 16
Remediation cost 5 min