Java 8 type output with non-stationary access to static members

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 I accidentally called a static method in an unsteady way. I know that you should not set static methods in a non-stationary way, but I'm still wondering why the type cannot be inferred in this case?

+8
java java-8 type-inference method-reference
source share
1 answer

In fact, the error says invalid method reference static bound method reference .

What makes sense if you know about four types of method references:

  • Link to the static method.
  • Link to the associated non-static method.
  • Reference to an unrelated non-static method.
  • Constructor Link

JLS explanation:

This is a compile-time error if the method reference expression is of the form ReferenceType :: [TypeArguments] Identifier, and the compile-time declaration is static, and ReferenceType is not a simple or qualified name

In addition to poor design, performance overhead to limit the recipient.

+4
source share

All Articles