Repository navigation
Description
Affects PMD Version: 7.28.0 (also 7.29.0-SNAPSHOT)
Description:
With d(int, int), d(long, Integer) and an Integer value, javac 21 rejects d(value, 5):
Example.java:6: error: reference to d is ambiguous
both method d(int,int) in Example and method d(long,Integer) in Example match
Both methods are applicable by loose invocation. For the second argument, int and Integer are not subtypes of each other, so neither method is more specific (JLS 15.12.2.5).
PMD resolves the call to d(int, int) and getOverloadSelectionInfo().isFailed() is false. PhaseOverloadSet.doInfer, called from isInferredMoreSpecific, compares the parameter types with checkConvertibleOrDefer:
pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/PhaseOverloadSet.java
Lines 166 to 187 in 5c9271c
| JMethodSig sfun = TypeOps.findFunctionalInterfaceMethod(si); | |
| JMethodSig tfun = TypeOps.findFunctionalInterfaceMethod(ti); | |
| if (sfun == null || tfun == null) { | |
| if (phase.canBox()) { | |
| JTypeMirror stdExprTy = ei.getStandaloneType(); | |
| if (stdExprTy != null | |
| // there is a boxing or unboxing conversion happening | |
| && stdExprTy.isPrimitive() != si.isPrimitive() | |
| && stdExprTy.isPrimitive() != ti.isPrimitive()) { | |
| // si or ti is more specific if it only involves | |
| // the boxing/unboxing conversion, without widening | |
| // afterwards. | |
| if (stdExprTy.box().equals(si.box())) { | |
| continue; | |
| } else if (stdExprTy.box().equals(ti.box())) { | |
| return false; | |
| } | |
| } | |
| } | |
| infer.checkConvertibleOrDefer(ctx, si, ti, ei, phase, site); | |
| continue; |
In the loose phase, when one of the two types is primitive, Infer.isConvertible boxes both before comparing them (Infer.java:1004-1012). The pair e(long, long) and e(Object, Object), two of the overloads of JUnit 4 Assert.assertEquals, behaves the same way. assertEquals(value, 5) is ambiguous for javac and resolves to assertEquals(long, long) in PMD.
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 d(value.intValue(), 5), which does not compile without it.
Code Sample demonstrating the issue:
class Example {
static void d(int x, int y) { }
static void d(long x, Integer y) { }
void test(Integer value) {
d(value, 5); // javac: reference to d is ambiguous
}
}Steps to reproduce:
javac Example.java, also with--release 8, fails with the error above.- Run PMD on
Example.javawith the XPath rule//MethodCall[pmd-java:matchesSig("Example#d(int,int)")]. It reports line 6.
Running PMD through: Other (PmdAnalysis API)
Activity
[java] UnnecessaryBoxing: rerun the overload resolution without the u…
[java] Fix pmd#7146, pmd#7149: Loose invocation conversion and the mo…
Enable test cases (pmd#7146, pmd#7149)