Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java,存储方法引用以供以后执行_Java - Fatal编程技术网

Java,存储方法引用以供以后执行

Java,存储方法引用以供以后执行,java,Java,在Java8中,我想存储方法引用 上下文是:我的程序现在可能无法执行方法,但必须在终止之前执行它们。所以我的目标是将这些方法存储在一个专用类中,该类将在程序终止之前执行它们 到目前为止,以下是我尝试的: 我有一个与方法原型匹配的接口: public interface IExecutable { public void method(String[] args); } 我有一个类,用来存储方法及其参数: import java.util.HashMap; import java.uti

在Java8中,我想存储方法引用

上下文是:我的程序现在可能无法执行方法,但必须在终止之前执行它们。所以我的目标是将这些方法存储在一个专用类中,该类将在程序终止之前执行它们

到目前为止,以下是我尝试的:

我有一个与方法原型匹配的接口:

public interface IExecutable {
    public void method(String[] args);
}
我有一个类,用来存储方法及其参数:

import java.util.HashMap;
import java.util.Map;

public class LateExecutor {

    private Map<String[], IExecutable> tasks = new HashMap<>();

    public void execute() {
        tasks.forEach((args, method) -> method(args));
    }

    public void storeTask(String[] args, IExecutable method) {
        tasks.put(args, method);
    }
}
但是对于
LateExecutor
类的当前状态,我在
->方法(
)上有以下错误:

类型LateExecutor的方法(字符串[])未定义

我理解,因为LateExecutor没有这种方法


然而,这给我留下了以下问题:如何存储方法引用并在以后执行它们(也欢迎任何其他解决我的问题的想法)。
方法
是可执行的
的名称,因此您需要执行
方法。方法(args)


您的地图具有可执行的
IExecutable
s实例,这就是您应该如何处理它们:

public void execute() {
    //better rename "method" to something like "executable"
    tasks.forEach((args, method) -> method.method(args));
}
forEach
lambda表达式中的
method
参数是一个
IExecutable
,该接口中方法的名称是
method



旁注:您不需要声明
IExecutable
。该方法签名有一个内置的函数接口:您可以使用
Consumer
(然后
accept(args)
调用该方法)

此签名仅用于测试。我的实际方法有几个参数。消费者是唯一可用的参数吗?回复:“旁注”。您不需要这样做,但通常有令人信服的理由这样做。通常,声明您自己的接口会增加语义值,而像
BiFunction
这样的东西是毫无意义的。同意在这种情况下
IExecutable
不会增加太多值,尽管我倾向于避免在泛型类型参数中使用数组,因为ey不会以大多数人觉得直观的方式进行交互。
String[]
只是您示例中的类型参数。您可以找到一组内置函数;请检查我假设的
object::method
语法是否有效。您需要用
@functionanterface
注释您的
IExecutable
接口
public void execute() {
    tasks.forEach((args, method) -> method.method(args));
}
public void execute() {
    //better rename "method" to something like "executable"
    tasks.forEach((args, method) -> method.method(args));
}