Skip to content

[java] UnnecessaryCast: False positive with package private methods #5732

Closed

Description

@hgschmie

Affects PMD Version:

7.13.0

Rule:

Please provide the rule name and a link to the rule documentation:
https://docs.pmd-code.org/latest/pmd_rules_java_codestyle.html#unnecessarycast

Description:

PMD gets confused with package private methods.

Code Sample demonstrating the issue:

package A;

public class Foo {
    String getAThing() {
        return "a thing";
    }
}
package B;

public class Bar extends Foo {
    public String getBThing() {
        return "b thing";
    }
}
package A;

import B.Bar;

public class Test {
    public static void main(String ... args) {
        Bar bar = new Bar();
        System.out.println(((Foo) bar).getAThing());
        System.out.println(bar.getBThing());
    }
}

The Test class must cast the Bar to a Foo to access the package private method getAThing(), otherwise it is package private in the B package, not the A package.

PMD reports PMD Failure: A.Test:8 Rule:UnnecessaryCast Priority:3 Unnecessary cast (Foo). for the line with the cast.

Expected outcome:

PMD should realize that, for a package private method, the cast is necessary to bring the object into the right package for package private access.

PMD reports a violation at line 8, but that's wrong. That's a false positive.

Running PMD through: Maven

Activity

  1. added
    a:false-positive
    on May 13, 2025
  2. added 2 commits that reference this issue on Aug 28, 2026
    1b890ed
    27e8062
  3. added this to the 7.28.0 milestone on Aug 30, 2026
  4. added a commit that references this issue on Aug 30, 2026
    4b366e0
  5. changed the title [-][java] UnnecessaryCast false positive with package private methods[/-] [+][java] UnnecessaryCast: False positive with package private methods[/+] on Aug 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positive

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions