gpt4 book ai didi

java - 在Java中将函数作为参数传递给方法并返回其返回值?

转载 作者:行者123 更新时间:2023-12-02 09:55:50 30 4
gpt4 key购买 nike

我的情况如下,我有一堆命令例如:

someService1.foo()
someService2.bar()

需要以两种不同的方式执行,一种是在修改的安全上下文中执行,有时无需修改安全上下文。现在我的计划是编写一个执行器,其结构应如下所示:

public Object runCommand(Runnable command){
if(someCondition){
//run command in modified context
} else {
//just run the command
}
}

我的主要问题是如何将命令的返回值返回给调用方法。因为Runnable的run()的返回类型是void。所以我想到使用 Callable 来实现这一点。但是这个问题有干净的通用方法吗?

最佳答案

您可以创建自己的接口(interface)(Runnable 也是接口(interface)),而不是使用 Runnable。如果您希望返回类型是通用的,您可以创建如下内容:

@FunctionalInterface
interface MyCommand<T> {
public T execute();
}

那么你的代码将变成:

public <T> T runCommand(MyCommand<T> command){
if(someCondition){
//Run it in context or whatever
return command.execute();
} else {
return command.execute();
}
}

你可以像这样使用它(完整代码在这里):

public class Test{

public static void main(String[] args) {
Test test=new Test();
String result1=test.runCommand(test::stringCommand);
Integer result2=test.runCommand(test::integerCommand);
Boolean result3 = inter.runCommand(new MyCommand<Boolean>() {
@Override
public Boolean execute() {
return true;
}
});
}

public String stringCommand() {
return "A string command";
}

public Integer integerCommand() {
return new Integer(5);
}

public <T>T runCommand(MyCommand<T> command){
return command.execute();
}
}

关于java - 在Java中将函数作为参数传递给方法并返回其返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56020595/

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