在java 8中,我想存储方法引用。
上下文是:我的程序现在可能无法执行方法,但必须在终止之前执行它们。所以我的目标是将这些方法存储在一个专用的类中,该类将在程序终止之前执行它们。
到目前为止,这是我尝试过的:
我有一个与方法原型(prototype)相匹配的接口(interface):
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);
}
}
有了这个,我想从另一个类中使用类似的东西调用 storeTask
:
lateExecutor.storeTask(arrayOfArgs, object::method)
但是根据 LateExecutor
类的当前状态,我在 -> 方法(
:
The method method(String[]) is undefined for the type LateExecutor
我理解是因为 LateExecutor 没有这个方法。
但是,这给我留下了以下问题:如何存储方法引用并稍后执行它们(也欢迎任何其他解决我的问题的想法)。
最佳答案
您的 map 包含 IExecutable
的实例s,这就是你应该如何对待他们:
public void execute() {
//better rename "method" to something like "executable"
tasks.forEach((args, method) -> method.method(args));
}
method
forEach
中的参数lambda 表达式是 IExecutable
,该接口(interface)中的方法名称为method
.
旁注:您不需要声明 IExecutable
。有一个带有该方法签名的内置函数接口(interface):您可以使用 Consumer<String[]>
(那么 accept(args)
将是您调用该方法的方式)
关于Java,存储方法引用以供以后执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60614271/