False positive compilation of a method reference with type parameters

B. Blaser bsrbnd at gmail.com
Sat Jan 25 12:50:08 UTC 2020


Nikita,

Maybe someone else could confirm but I believe the current behavior is
correct, see JLS §15.12.2.1 [1]:

"This clause implies that a non-generic method may be potentially
applicable to an invocation that supplies explicit type arguments.
Indeed, it may turn out to be applicable. In such a case, the type
arguments will simply be ignored."

Which means that "cons(int var)" is potentially applicable too and is
also the chosen one. Simply try to remove it and the compilation will
fail as expected.

Best regards,
Bernard

On Thu, 23 Jan 2020 at 15:00, Nikita Eshkeev <neshkeev at yandex.ru> wrote:
>
>
> [DUPLICATED FROM jdk-dev]
>
>
> Greetings,
>
> I expect the compilation of the following code should fail, but the
> compilation is successful:
>
> public class Demo {
>     static <T> void cons(T c) { System.out.println(c.getClass()); }
>     static void cons(int var) { System.out.println("int"); }
>
>     public static void main(String[] args) {
>         java.util.function.IntConsumer cons1 = Demo::<String>cons; // <-- the type parameter is ignored
>         java.util.function.Consumer<Integer> cons2 = Demo::<String>cons; // <-- wrong type parameter for the consumer
>         cons1.accept(5);
>         cons2.accept(5);
>     }
> }
>
> $ javac Demo.java ; java Demo
> int
> int
>
> I checked for both java-8
> $ java -version
> openjdk version "1.8.0_232"
> OpenJDK Runtime Environment (build 1.8.0_232-b09)
> OpenJDK 64-Bit Server VM (build 25.232-b09, mixed mode)
>
> and java-11:
> $ java -version
> openjdk version "11.0.5" 2019-10-15
> OpenJDK Runtime Environment (build 11.0.5+10)
> OpenJDK 64-Bit Server VM (build 11.0.5+10, mixed mode)
>
> My OS: Arch Linux funcs 5.4.8-arch1-1 #1 SMP PREEMPT Sat, 04 Jan 2020
> 23:46:18 +0000 x86_64 GNU/Linux
>
> --
> Sincerely,
> Nikita Eshkeev
>


More information about the jdk-dev mailing list