You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让作为函数参数传入的Callable新实例的call方法支持接收参数

问题核心

你使用的java.util.concurrent.Callable接口的call()方法原生是无参定义,无法直接在调用时传入自定义参数,要实现带参回调可以用两种方案:


方案1:自定义回调接口(兼容性最好,全Java版本可用)

  1. 先定义带参数的回调函数式接口:
@FunctionalInterface
public interface ParamCallback<P, R> {
    // P是参数类型,R是返回值类型
    R call(P param);
}
  1. 修改doSomething方法的入参类型,在内部触发回调时传入对应参数:
public void doSomething(ParamCallback<String, Void> callback) {
    // 事件触发时获取要传递的参数
    String triggerParam = "事件触发时的动态参数";
    // 调用回调并传入参数
    callback.call(triggerParam);
}
  1. 调用写法和你预期的完全一致:
doSomething(new ParamCallback<String, Void>() {
    @Override
    public Void call(String foo) {
        System.out.println("callback called with string " + foo);
        return null;
    }
});
// Java 8及以上版本可以简化为Lambda写法
doSomething(foo -> {
    System.out.println("callback called with string " + foo);
    return null;
});

方案2:使用Java 8+自带函数式接口(无需自定义接口,代码更简洁)

如果你的回调不需要返回值,直接用自带的java.util.function.Consumer<T>接口即可,它的accept(T t)方法刚好满足接收一个参数、无返回值的需求:

  1. 修改doSomething方法的入参类型:
import java.util.function.Consumer;

public void doSomething(Consumer<String> callback) {
    String triggerParam = "事件触发时的动态参数";
    callback.accept(triggerParam);
}
  1. 调用代码:
doSomething(new Consumer<String>() {
    @Override
    public void accept(String foo) {
        System.out.println("callback called with string " + foo);
    }
});
// Lambda简化版
doSomething(foo -> System.out.println("callback called with string " + foo));

如果你的回调需要返回值,可以改用Function<T, R>接口,T是入参类型,R是返回值类型。


内容的提问来源于stack exchange,提问作者molecule

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:27:03