Consider the following code:
class Test {
void accept(Consumer<Integer> c) {}
static void consumer(Integer i) {}
void foo() {
accept(this::consumer); // The method accept(Consumer<Integer>) in the type Test is not applicable for the arguments (this::consumer)
accept(Test::consumer); // Valid
}
}
I came across this the other day when accidentally calling a static method in a non-static way. I know that you shouldn't call static methods in a non-static way, but I am still wondering, why isn't it possible to infer the type in this case?
Actually error says invalid method reference static bound method reference
.
Which makes sense if you know about four types of methods references:
JLS explanation:
It is a compile-time error if a method reference expression has the form ReferenceType :: [TypeArguments] Identifier, and the compile-time declaration is static, and ReferenceType is not a simple or qualified name
In addition to bad design there is performance overhead for capturing (bounding) the receiver.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With