Skip to content

Conversation

@zbynek
Copy link
Contributor

@zbynek zbynek commented Aug 31, 2025

Describe the PR

There is a false negative in the UnnecessaryCast rule when an object is cast just to call a method that's available on its declared type. Example:

class A {
    private Integer x;

    public Integer getX() {
        return x;
    }

    public static class B extends A { }

    public int compareTo(A arg) {
        return ((B) arg).getX().compareTo(getX()); // should be a violation
    }
}

We can simply call arg.getX() without casting it to B.

Related issues

This is somewhat similar to #3219, but in this PR I focused on the case when the cast is on methods's receiver, not its arguments.

Ready?

  • Added unit tests for fixed bug/feature
  • Passing all unit tests
  • Complete build ./mvnw clean verify passes (checked automatically by github actions)
  • Added (in-code) documentation (if needed)

@zbynek zbynek marked this pull request as draft August 31, 2025 16:05
@pmd-actions-helper
Copy link
Contributor

pmd-actions-helper bot commented Aug 31, 2025

Documentation Preview

Compared to main:
This changeset changes 0 violations,
introduces 6 new violations, 0 new errors and 0 new configuration errors,
removes 0 violations, 0 errors and 0 configuration errors.

Regression Tester Report

(comment created at 2025-09-17 22:17:46+00:00 for b7456fe)

@oowekyala
Copy link
Member

Note that this is in principle the same problem as #5948, you need to check that the selected overload is the same. I would like the logic to be shared if possible.

@oowekyala oowekyala changed the title Check unnecessary casts in method calls [java] Check unnecessary casts in method calls Sep 1, 2025
@zbynek zbynek marked this pull request as ready for review September 6, 2025 11:28
@adangel adangel added the a:false-negative PMD doesn't flag a problematic piece of code label Sep 19, 2025
@adangel adangel changed the title [java] Check unnecessary casts in method calls [java] Fix UnnecessaryCast false-negative in method calls Sep 19, 2025
@adangel adangel added this to the 7.18.0 milestone Sep 19, 2025
Copy link
Member

@adangel adangel left a comment

Choose a reason for hiding this comment

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

Thanks!

@adangel adangel merged commit e178ea9 into pmd:main Sep 19, 2025
12 checks passed
adangel added a commit that referenced this pull request Sep 19, 2025
adangel added a commit to adangel/pmd that referenced this pull request Sep 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

a:false-negative PMD doesn't flag a problematic piece of code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants