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

sqr*_*pin 8 java type-inference java-8 method-reference

请考虑以下代码:

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
    }

}
Run Code Online (Sandbox Code Playgroud)

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

use*_*306 4

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

如果您了解四种类型的方法引用,这就有意义了:

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

JLS解释:

如果方法引用表达式的格式为 ReferenceType :: [TypeArguments] Identifier,并且编译时声明是静态的,并且 ReferenceType 不是简单名称或限定名称,则这是编译时错误

除了糟糕的设计之外,捕获(限制)接收器还会带来性能开销。