# 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);

🛠️ Auto-refactor Available

You can auto refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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