奇怪的构造,java 将静态方法转换为 class

Odd construction, java converting static method to class

我最近偶然发现了一段代码,以我对 java 的理解无法解释。我已经创建了同种结构的这个小版本:

public class StaticMethodClass {
    static void IDK(Integer i, String somethingElse) {
        System.out.println("It has been done");
    }

    public static void main(String... whatever) {
        Action.ITEM.doStuff();
    }
}

interface Func {
    void exec(Integer i, String somethingElse);
}

enum Action {
    ITEM(StaticMethodClass::IDK);

    private Func f;

    Action(Func f){
        this.f = f;
    }

    void doStuff() {
        this.f.exec(1, "huh");
    }
}

我无法按照 Action.ITEM 的构造方式围绕它的部分,因为它应该得到一个 class 实现 Func 接口。相反,它传递了一个方法,该方法以某种方式隐式转换。

我的问题是它是如何工作的,以及这里适用的规则。

这是一个相对较新的构造,称为 method reference。直到 Java 8.

才可用

I can't wrap my head around it the way Action.ITEM is constructed, as it should get a class implementing the Func interface.

方法引用提供了创建此类实现的快捷方式:而不是您编写

ITEM((i, e) -> StaticMethodClass.IDK(i, e));

编译器会通过 "shortcut" 语法为您计算出来,只要 IDK 方法的签名与 Funcexec方法。

注:以上Lambda版本本身就是

的快捷方式
ITEM(new Func() {
    @Override public exec(Integer i, String somethingElse) { 
        StaticMethodClass.IDK(i, somethingElse);
    }
});

所以方法参考是捷径的捷径。