Skip to content

[java] UnnecessaryBoxing: False negative when another overload takes an unrelated reference type #7134

Open

Description

@saryn17

Affects PMD Version: 7.17.0 to 7.28.0

Rule: UnnecessaryBoxing
https://docs.pmd-code.org/latest/pmd_rules_java_codestyle.html#unnecessaryboxing

Description:

#5971 (7.17.0, the fix for #5948) added an overload check to this rule. Its last clause suppresses the warning for any overload with a reference type at the argument position:

return overloads.stream()
.filter(overload -> !overload.equals(currentMethod))
.filter(overload -> argIndex < overload.getFormalParameters().size())
.map(overload -> overload.getFormalParameters().get(argIndex))
.anyMatch(overloadParamType ->
// Boxed type is assignable to overload parameter (Object, generic, etc.)
boxedType.isSubtypeOf(overloadParamType)
// Or overload takes reference type while current takes primitive (different conversion paths)
|| overloadParamType.isTypeVariable() || !overloadParamType.isPrimitive() && currentParamType.isPrimitive()
);

currentParamType is always primitive at that point (early return at L243), so the clause does not check whether the boxed argument can be passed to that overload. In the sample, call(String) hides the warning, although call(value) compiles and still calls call(int) (JLS 15.12.2.3).

PMD 7.16.0 reports line 6. 7.17.0 and 7.28.0 don't.

Code Sample demonstrating the issue:

class Example {
    static void call(int value) { }
    static void call(String value) { }

    void test(Integer value) {
        call(value.intValue());
    }
}

JDK calls are affected the same way, e.g. new StringBuilder(n.intValue()) because of StringBuilder(String), and new ArrayList<>(n.intValue()) because of ArrayList(Collection).

Expected outcome:

PMD should report a violation at line 6, but doesn't. This is a false-negative.

Running PMD through: Other (PmdAnalysis API)

Activity

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions