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

Java如何实现带类型自动推导的Lambda链式数据转换任务

Java链式Lambda数据转换实现方案

原有实现的核心问题

原有方案的泛型信息没有跟随链式调用传递,使用List<Middleware<?, ?>>存储执行步骤会在编译期丢失前后步骤的输入输出类型对应关系,既无法实现编译期类型安全校验,也无法支持自动类型推导。

基础接口定义

你原有的Middleware接口无需修改,补充缺失的Callback函数式接口:

@FunctionalInterface
public interface Callback<R> {
    void onResult(R result);
}

@FunctionalInterface
public interface Middleware<I, O> {
    O run(I data);
}

MyTask完整实现

核心思路为:每次调用start/then方法时,返回持有新输出类型的MyTask实例,直接组合前后步骤的执行逻辑,无需用列表存储所有中间件,从根源避免泛型类型丢失问题:

import java.util.function.Supplier;

public class MyTask<T> {
    private final Supplier<T> executionLogic;

    // 内部构造方法,用于链式调用生成新实例
    private MyTask(Supplier<T> executionLogic) {
        this.executionLogic = executionLogic;
    }

    // 对外构造方法,传入初始数据
    public MyTask(T initialData) {
        this(() -> initialData);
    }

    // 第一个执行步骤,接收初始数据生成第一个输出
    public <O> MyTask<O> start(Middleware<T, O> firstMiddleware) {
        return new MyTask<>(() -> firstMiddleware.run(executionLogic.get()));
    }

    // 后续链式步骤,以上一步输出作为当前步骤输入
    public <O> MyTask<O> then(Middleware<T, O> nextMiddleware) {
        return new MyTask<>(() -> nextMiddleware.run(executionLogic.get()));
    }

    // 触发执行,支持异步改造
    public void execute(Callback<T> resultCallback) {
        // 同步执行逻辑
        T finalResult = executionLogic.get();
        resultCallback.onResult(finalResult);

        // 如需异步执行,替换为以下逻辑即可:
        // new Thread(() -> {
        //     T finalResult = executionLogic.get();
        //     resultCallback.onResult(finalResult);
        // }).start();
    }
}

调用验证

完全符合你期望的调用写法,运行后输出The answer is 5:

public class Main {
    public static void main(String[] args) {
        new MyTask(null).start((d) -> {
            return 1.25f;
        }).then((f) -> {
            return (int)(f*4);
        }).then((i) -> {
            return ""+i;
        }).then((s) -> {
            return "The answer is "+s;
        }).execute((r) -> {
            System.out.println(r);
        });
    }
}

泛型特性说明

该实现全程由编译器自动推导每一步的输入输出类型,无需手动指定泛型参数,且能在编译期校验类型不匹配问题,完全保证类型安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:45:00