Consumer bla = new Bla()::shake;
is equivalent to
Consumer<Object> bla = new Bla()::shake;
which is equivalent to (*)
Consumer<Object> bla = (Object x) -> new Bla().shake(x);
Even if you had specified the intended generic type parameter Integer
, i.e.
Consumer<Integer> bla = new Bla()::shake;
it is equivalent to
Consumer<Integer> bla = (Integer x) -> new Bla().shake(x);
Java method resolution is a 3-step search:
Match without using boxing, unboxing, or var-args.
Match using boxing and unboxing, but no var-args.
Match all.
Since shake(Object)
matches in the first step, that is the method used, even for Integer
type parameter.
To get the shake(int)
overload, you must either remove the shake(Object)
overload, or pass a primitive integer value (byte
, short
, char
, or int
), which means you can make it work one of these ways:
Consumer<Integer> bla = x -> new Bla().shake((int) x);
Consumer<Integer> bla = x -> new Bla().shake(x.intValue());
IntConsumer bla = new Bla()::shake; // Recommended solution
(*) It's not quite equivalent: it's more like:
Bla instance = new Bla();
Consumer<Object> bla = (Object x) -> instance.shake(x);
This detail is omitted above to focus on method signature resolution.
Consumer
is generic, so its parameter is a reference type. – Andy Turner Jan 3 '20 at 9:35