Pattern Matching for instanceof & Record Patterns (Java 21+)
1Concept
Java 16 introduced pattern matching for `instanceof`, eliminating redundant casts (`if (obj instanceof String s)`). Java 21 added Record Patterns (JEP 440), enabling direct deconstruction of record components directly in `if` and `switch` expressions.
2Architecture Diagram
Old Java: if (obj instanceof Point) { Point p = (Point) obj; int x = p.x(); }
Java 21: if (obj instanceof Point(int x, int y)) { ... direct access to x, y! }3Code Example
Core Java
public class RecordPatternsDemo {
record Point(int x, int y) {}
record Box(Point topLeft, Point bottomRight) {}
public static void printPoint(Object obj) {
// Record deconstruction pattern
if (obj instanceof Point(int x, int y)) {
System.out.println("Deconstructed Point -> X: " + x + ", Y: " + y);
}
}
public static void main(String[] args) {
Point p = new Point(10, 25);
printPoint(p);
}
}4Expected Output
Deconstructed Point -> X: 10, Y: 25
5Key Takeaways
- ✓Record patterns deconstruct nested records cleanly without manual accessor calls.
- ✓Eliminates ClassCastException and eliminates boilerplate getter calls.
- ✓Combines with switch expressions for high-level functional data extraction.