gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:26:45 25 4
gpt4 key购买 nike

在 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像这样,来自另一个类(class):
lateExecutor.storeTask(arrayOfArgs, object::method)

但随着 LateExecutor 的当前状态类,我在 -> method( 上有以下错误:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com