Skip to content

[java] Type-name-qualified invocation filters out instance methods before overload resolution #7152

Open

Description

@saryn17

Affects PMD Version: 7.28.0 (also 7.29.0-SNAPSHOT)

Description:

In the sample, m(Object) is applicable to Foo.m(value) by strict invocation and is the compile-time declaration, so javac 21 rejects the call:

Foo.java:6: error: non-static method m(Object) cannot be referenced from a static context

javac searches all member methods (JLS 15.12.2.1) and checks the modifier after choosing the most specific one: "the compile-time declaration must be static, or a compile-time error occurs" (JLS 15.12.3).

For TypeName.m(args), MethodInvocMirror.getAccessibleCandidates passes staticOnly = true and TypeOps.getMethodsOf drops the instance methods:

boolean staticOnly = lhs instanceof ASTTypeExpression;
return TypeOps.getMethodsOf(lhsType, getName(), staticOnly, myNode.getEnclosingType().getSymbol());

PMD does not see m(Object). It resolves the call to m(int) and getOverloadSelectionInfo().isFailed() is false. With an interface as qualifier, only the static methods declared in the interface are candidates (TypeOps.java:2077-2080), so an abstract or default method is skipped the same way.

Found while working on #7136, where UnnecessaryBoxing reruns the overload resolution without the unboxing. It resolves the call without intValue() and reports value.intValue() in Foo.m(value.intValue()), which does not compile without it.

Code Sample demonstrating the issue:

public class Foo {
    static void m(int x) { }
    void m(Object o) { }

    void t(Integer value) {
        Foo.m(value); // javac: non-static method m(Object) cannot be referenced from a static context
    }
}

Steps to reproduce:

  1. javac Foo.java, also with --release 8, fails with the error above.
  2. Run PMD on Foo.java with the XPath rule //MethodCall[pmd-java:matchesSig("Foo#m(int)")]. It reports line 6.

Running PMD through: Other (PmdAnalysis API)

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