Visitar URL original
Keep unconditional `instanceof` checks before Java 21 in `InstanceOfPatternMatch` by timtebeek · Pull Request #1181 · openrewrite/rewrite-static-analysis · GitHub
Skip to content

Keep unconditional instanceof checks before Java 21 in InstanceOfPatternMatch - #1181

Merged
timtebeek merged 1 commit into
mainfrom
instanceof-unconditional-pattern-before-java21
Nov 3, 2026
Merged

timtebeek merged 1 commit into
mainfrom
instanceof-unconditional-pattern-before-java21

Conversation

@timtebeek

@timtebeek timtebeek commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

InstanceOfPatternMatch runs on Java 17 sources, but before Java 21 a type pattern must not be unconditional. When the static type of the expression is already a subtype of the tested type, javac rejects the pattern with "expression type is a subtype of pattern type".

ObjectStateMachine<S, E> machine = create();   // ObjectStateMachine implements BeanNameAware
if (machine instanceof BeanNameAware) {
    ((BeanNameAware) machine).setBeanName(beanName);
}

became

if (machine instanceof BeanNameAware aware) {
    aware.setBeanName(beanName);
}

This surfaced while validating the Spring Boot 4.1 migration over open source Spring Boot 3.x repositories: in spring-projects/spring-statemachine (ObjectStateMachineFactory, Java 17) the result no longer compiles with expression type ObjectStateMachine<S,E> is a subtype of pattern type BeanNameAware.

The change leaves an instanceof alone when its expression type is assignable to the tested type and the source file's Java version is below 21 (or unknown). On Java 21 and later, where unconditional patterns are allowed, the recipe behaves as before.

Is this the right change?

Tests: InstanceOfPatternMatchTest gains a no-change test on Java 17 (fails without the fix) and a change test on Java 21; all 72 tests in InstanceOfPatternMatchTest pass, as does RemoveInstanceOfPatternMatchTest.

…atternMatch`

Before Java 21 a type pattern must not be unconditional, so `machine instanceof BeanNameAware aware`
fails to compile when `machine` is already a `BeanNameAware`.
@github-project-automation github-project-automation Bot moved this to In Progress in OpenRewrite Nov 3, 2026
@timtebeek
timtebeek merged commit 3a93e85 into main Nov 3, 2026
1 check passed
@timtebeek
timtebeek deleted the instanceof-unconditional-pattern-before-java21 branch November 3, 2026 12:13
@github-project-automation github-project-automation Bot moved this from In Progress to Done in OpenRewrite Nov 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

1 participant