A type pattern combines an instanceof type test with a variable binding. Since Java 16, it can replace the repeated check, cast, and variable declaration required by older Java code. section 5.3.1
Binding after the type test
if (obj instanceof MyType myType) { // Use myType. } The pattern-based instanceof expression avoids the ClassCastException risk of an unchecked explicit cast. Older equivalent code repeats MyType in the test, cast, and declaration, creating opportunities for typos or refactoring mistakes. section 5.3.1
Use type patterns as part of a broader cast-safety practice:
- Prefer a narrower parameter type when a method accepts only that type; otherwise validate an Object parameter before delegating. section 5.3.1
- Do not copy equals() implementations without updating cast types; generate them with IDE features instead. section 5.3.1
if (obj instanceof MyType myType) {
… // Use myType.
}
Shows the compact Java 16 form that tests obj and binds myType for the guarded block. section 5.3.1
