liveBook · Manning

Type pattern

As explained in 100 Java Mistakes and How to Avoid Them

A type pattern is a Java pattern that tests whether a value has a specified type and binds it to a variable of that type.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains the Java 16 syntax, contrasts older repetition, and stops short of broader pattern-language details.
Examples
Uses guarded MyType binding, Point.equals(), Object-to-String processing, and repeated casts in a loop.
What it assumes
Assumes familiarity with Java casts, instanceof, method parameters, and equals() implementations.
What you can do after
Apply type patterns to replace guarded casts and recognize when method signatures should express narrower accepted types.
How it connects
Connects instanceof expressions with explicit casts, ClassCastException, getClass(), and equals().

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.