【问题标题】:How to accept parameters in a new Callable instance passed as a function parameter如何接受作为函数参数传递的新 Callable 实例中的参数
【发布时间】:2021-10-01 20:55:36
【问题描述】:

我是 Java 新手,我尝试将函数作为参数传递,当某个事件发生时会调用该函数。我遇到了 Callable 并找到了一些类似问题的答案,但并非完全如此。

目前,我的代码正在这样做

doSomething(new Callable<Void>() {
  public Void call() {
    System.out.println("callback called! ");
    return null;
  }
});

但我想要这个:

doSomething(new Callable<Void>() {
  public Void call(String foo) { // Want this function to accept parameters
    System.out.println("callback called with string " + foo);
    return null;
  }
});

【问题讨论】:

标签: java callback


【解决方案1】:

java.util.function.Consumer 函数式接口正是您所寻找的:接受单个参数并且不返回任何输出。

您需要执行以下操作:

    doSomething(new Consumer<String>() {
        @Override
        public void accept(String foo) {
            System.out.println("Consumer called with string " + foo);
        }
    });

或者更好,用 lambda 替换它:

doSomething(foo -> System.out.println("Consumer called with string " + foo));

doSomething 看起来像这样:

void doSomething(Consumer<String> stringConsumer) {
    stringConsumer.accept("Hello!");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-25
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 2022-01-09
    • 2021-01-14
    相关资源
    最近更新 更多