如何在 Java 中传递和调用方法引用

Eph*_*era 6 java java-8 method-reference

假设我有一个名为 的类Server,我想让其他Plugins人为它编写代码。SayPlugin是一个接口,它扩展Runnable并添加了一个方法:void init(...). 插件的工作是收集数据并将其发送到服务器。然而,当需要向服务器发送数据时,它是如何做到的呢?来自 C 和 C++ 我正在寻找沿着函数指针的思路。尽管我没有在 Java 标准类库之外找到示例,但在 Java 中似乎是可能的。

我如何将方法引用传递给init方法,以便它可以由 存储Plugin,然后我如何在插件想要发送数据时调用该方法?现在说所需的 Server 方法是:void sendData(Integer data)

例如:

// Inside Server
Plugin p = new PluginImplementation();
p.init(this::sendData);    

// Plugin init
public void init(?? sendMethod) {
    storedSendMethod = sendMethod;
    // ...
}

// Plugin run
public void run() {
    // ...
    storedSendMethod(x) // Sends data to server
    // ...
}
Run Code Online (Sandbox Code Playgroud)

alf*_*sin 5

使用java.util.function.Function我们可以将函数作为参数传递给方法,然后使用apply()将其应用于相关参数。这是一个例子:

import java.util.function.Function;

public class FunctionDemo {

    // we will pass a reference to this method
    public static Integer square(Integer x) {
        return x * x;
    }

    // this method accepts the function as an argument and applies it to the input: 5
    public static Integer doSomething(Function<Integer, Integer> func) {
        return func.apply(5);
    }

    public static void main(String[] args) {
        // and here's how to use it
        System.out.println(doSomething(FunctionDemo::square)); // prints 25
    }   
}
Run Code Online (Sandbox Code Playgroud)

具有多个参数的附加版本(作为数组传递):

public static Integer sum(Integer[] x) {
    Integer result = 0;
    for(int i = 0; i < x.length; i++)
        result += x[i];
    return result;
}

public static void main(String[] args) {
    Integer[] arr = {1,2,3,4,5};
    System.out.println(doSomething(Play::sum, arr));
}

public static Integer doSomething(Function<Integer[], Integer> func,
                                  Integer[] arr) {        
    return func.apply(arr);
}
Run Code Online (Sandbox Code Playgroud)