Skip to content

[java] Fix #6409: UnnecessaryCast false positive for anonymous class - #7193

Merged
adangel merged 2 commits into
pmd:mainfrom
ybai08:issue-6409-unnecessarycast-anonymous-class
Oct 29, 2026
Merged

adangel merged 2 commits into
pmd:mainfrom
ybai08:issue-6409-unnecessarycast-anonymous-class

Conversation

@ybai08

@ybai08 ybai08 commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Describe the PR

UnnecessaryCast reports the cast in

return list.stream().map(i -> (Foo) new Foo(){}).toList();

but the cast is needed. Without it, javac infers Stream<anonymous Foo> and fails with
List<<anonymous Foo>> cannot be converted to List<Foo>.

Cause: PMD gives new Foo() {} the type Foo, the instantiated type, not the anonymous
class. So operandType.equals(coercionType) in isCastUnnecessary is true, and the cast
is reported as an identity cast before the existing lambda-return check (#5073, #5440)
can run.

Fix: when the operand is an anonymous class creation, the rule uses
getAnonymousClassDeclaration().getTypeMirror() as the operand type. The unresolved-type
early return still runs on the original type first. After that the cast goes through the same
checks as a cast of a named subtype ((Foo) new FooImpl()), which is already not reported
in this position.

Behaviour change to be aware of: a cast of an anonymous class in a lambda return position
with an explicit target, e.g. Function<Integer, Foo> f = i -> (Foo) new Foo(){};, is no
longer reported. That matches what the rule already does for
i -> (Foo) new FooImpl() and i -> (Object) "s" on main. Casts in assignment
contexts (Foo f = (Foo) new Foo(){};, Runnable r = (Runnable) new Runnable() {...};)
are still reported. A new test covers those.

Tests added to UnnecessaryCast.xml:

  • #6409 False positive for anonymous class in lambda return of generic method: the
    Stream.map(...).toList() case from the issue, plus an Optional.map(...).orElse(...)
    variant. Expects 0 violations. I compiled both with javac 21: they compile with the
    casts and fail without them.
  • #6409 Unnecessary cast of anonymous class to its supertype: three assignment-context
    casts that should still be reported.

Related issues

Ready?

  • Added unit tests for fixed bug/feature
  • Passing all unit tests (only the pmd-java module was run locally; see below)
  • Complete build ./mvnw clean verify passes (checked automatically by github actions)
  • Added (in-code) documentation (if needed)

What was run locally (macOS, JDK 21.0.12):

  • ./mvnw -pl pmd-java test -Dtest=UnnecessaryCastTest: the new FP test fails without the
    fix (expected: <0> but was: <2>) and passes with it.
  • ./mvnw -pl pmd-java verify: BUILD SUCCESS, 10319 tests, 0 failures, 21 skipped.
    0 Checkstyle violations. The PMD self-check reports the same 6 existing
    AlwaysCallSuperWhenNotUsingRuleChain warnings as main (none in the changed file).
    japicmp ran. On main at 66860e2 the same command gives 10317 tests and the same
    6 warnings.
  • Not run: the full multi-module ./mvnw clean verify, and the pmd-regression-tester.
    The latter is the one that would show the effect on real-world projects.

The release notes have an entry under java-codestyle.

PMD types an anonymous class creation like `new Foo() {}` as `Foo`,
so the rule saw `(Foo) new Foo() {}` as an identity cast and reported
it. The type of the expression is the anonymous class, a strict subtype
of `Foo`. In a lambda returned to a generic method such as
`stream.map(i -> (Foo) new Foo() {}).toList()` the cast decides the
inferred type, and removing it does not compile.

The rule now uses the anonymous class type for the operand, so these
casts follow the same checks as casts of any other subtype.
@pmd-actions-helper

Copy link
Copy Markdown
Contributor

Documentation Preview

Compared to main:
This changeset changes 0 violations,
introduces 0 new violations, 0 new errors and 0 new configuration errors,
removes 0 violations, 16 errors and 9 configuration errors.
There are 0 changed duplications, 0 new duplications and 0 removed duplications.
There are 0 changed CPD errors, 0 new CPD errors and 0 removed CPD errors.

Regression Tester Report

(comment created at 2026-10-17 20:50:37+00:00 for 02cc797)

@adangel adangel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@adangel adangel added this to the 7.29.0 milestone Oct 29, 2026
@adangel
adangel merged commit 1f563e2 into pmd:main Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[java] UnnecessaryCast: False positive for anonymous class in Stream.map() with toList()

3 participants