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

标签 java generics

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

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/

相关文章:

java - 我如何模拟 GoogleCredential 以测试我的业务逻辑

java - 根据传递的对象类型进行多次操作

java - 如何将 Class<?> 与 Hamcrest Matcher 中的特定 Class 实例进行匹配?

使用用户定义的类的 C# 泛型类型

swift - 用于 nil 过滤的通用 Swift 字典扩展

java - 向 JPane 添加操作监听器或 if 语句

java - 为什么我的 Testcontainers 测试会挂起直到 "Waiting for database connection to become available at"超时?

java - 如何接收来自服务器的 UDP 数据包?对于安卓 Java

Java 接口(interface)反射替代方案

java - 如何用通用方法找出最小值?