Pattern matching for instanceof
Combine type check and cast in one step with pattern matching.
Porównanie kodu
✕ Java 8
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.length());
}
✓ Java 16+
if (obj instanceof String s) {
IO.println(s.length());
}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
No redundant cast
Type check and variable binding happen in a single expression.
Fewer lines
One line instead of two — the cast line disappears entirely.
Scope safety
The pattern variable is only in scope where the type is guaranteed.
Stare podejście
instanceof + Cast
Nowoczesne podejście
Pattern Variable
Od JDK
16
Poziom trudności
Początkujący
Wsparcie JDK
Pattern matching for instanceof
Dostępne
Widely available since JDK 16 (March 2021)
Jak to działa
Pattern matching for instanceof eliminates the redundant cast after a type check. The variable is automatically scoped to where the pattern matches, making code safer and shorter.
Powiązana dokumentacja