Java 8 静态成员的非静态访问的类型推断

Java 8 type inference with non-static access of static members

考虑以下代码:

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
    }

}

前几天我不小心以非静态方式调用静态方法时遇到了这个问题。 我知道你不应该以非静态方式调用静态方法,但我仍然想知道,为什么在这种情况下不能推断类型?

实际上错误说 invalid method reference static bound method reference

如果您 know about 引用了四种方法,这就有意义了:

  1. 对静态方法的引用。
  2. 引用绑定的非静态方法。
  3. 引用未绑定的非静态方法。
  4. 对构造函数的引用

JLS 说明:

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

除了糟糕的设计之外,还有捕获(绑定)接收器的性能开销。