Java中如何将Function<X,Y>作为Function<Object,Object>使用
问题根源
- 类型转型逻辑错误:Java仅支持子类自动向上转型为父类,父类实例无法直接向下转型为子类。你将MyFunction实现的Function入参固定为
Object类型,lambda中的input默认是Object类型,而myMethod要求入参为MyClass(Object的子类),无显式强转时直接传入自然会触发类型不匹配报错。 - 泛型通配符使用不符合规范:通配符
?仅可用于标识变量/参数的未知类型,不能作为类实现的父接口的泛型参数,因此implements Function<? super Object, MyList<? extends Object>>属于非法写法,会触发A supertype may not specify any wildcard报错。 - 自定义类未绑定泛型参数:你将MyFunction的入参、返回值类型提前写死,自然无法适配任意输入输出类型的Function,也无法实现类型安全的函数链式传递。
解决方案
要实现类型安全的任意输入输出类型函数链,只需要将MyFunction定义为带两个泛型参数的泛型类,分别绑定入参类型和返回值类型,同时封装Java原生Function自带的andThen链式调用能力即可,示例实现如下:
import java.util.function.Function; // T为当前函数入参类型,R为当前函数返回值类型 public class MyFunction<T, R> implements Function<T, R> { private final Function<T, R> delegate; public MyFunction(Function<T, R> delegate) { this.delegate = delegate; } @Override public R apply(T input) { return delegate.apply(input); } // 拼接下一个函数,自动匹配前一个函数的输出为后一个函数的输入 public <V> MyFunction<T, V> andThen(MyFunction<R, V> next) { return new MyFunction<>(delegate.andThen(next)); } // 测试用自定义方法 public static MyList<String> myMethod(MyClass myClass) { return new MyList<>(); } // 测试用链式调用第二个方法 public static Integer countListSize(MyList<String> list) { return list.size(); } public static void main(String[] args) { // 构造第一个函数:入参MyClass,返回MyList<String> MyFunction<MyClass, MyList<String>> func1 = new MyFunction<>(MyFunction::myMethod); // 构造第二个函数:入参MyList<String>,返回Integer MyFunction<MyList<String>, Integer> func2 = new MyFunction<>(MyFunction::countListSize); // 拼接为完整函数链:入参MyClass,返回Integer MyFunction<MyClass, Integer> functionChain = func1.andThen(func2); // 测试调用 MyClass input = new MyClass(); Integer result = functionChain.apply(input); System.out.println(result); } } // 示例辅助类定义,替换为你自己的实现即可 class MyList<T> { public int size() { return 0; } } class MyClass {}
如果不需要编译期类型检查,只想快速跑通你最初的代码,只需要在lambda中添加强制类型转换即可,但是该写法运行时如果传入非MyClass类型的参数会直接抛出ClassCastException,不推荐生产环境使用:
MyFunction myFunction = new MyFunction(input -> myMethod((MyClass) input));
内容的提问来源于stack exchange,提问作者pacman
相关产品推荐
相关产品推荐

