【发布时间】:2021-03-03 08:44:39
【问题描述】:
今天我遇到了以下 Java 作业,但我不知道如何通过类型擦除。
任务是创建一个通用 InputConverter 类,该类接受 T 类型的输入并使用作为方法参数接收的多个函数链对其进行转换。它必须支持以下符号:
Function<String, List<String>> lambda1 = ...;
Function<List<String>, String> lambda2 = ...;
Function<String, Integer> lambda3 = ...;
String input = ...;
List<String> res1 = new InputConverter(input).convertBy(lambda1);
Integer res2 = new InputConverter(input).convertBy(lambda1, lambda2, lambda3);
这是我想出的:
import java.util.Arrays;
import java.util.function.Function;
public class InputConverter<T> {
private final T input;
public InputConverter(T input) {
this.input = input;
}
public <B> B convertBy(Function<T, ?> first, Function<?, ?>... functions) {
var res = first.apply(input);
Function<?, B> composed = Arrays.stream(functions)
.reduce(Function::andThen)
.orElse(Function.identity());
return composed.apply(res);
}
}
这当然行不通,因为我找不到确定最后一个函数的返回类型的方法。
注意事项:
- InputConverter 应该只定义一个
convertBy方法,因此方法重载不是一种选择。 - 此方法应返回链中最后一个函数的结果,无需显式强制转换。
【问题讨论】:
-
你确定分配有任意数量的函数作为参数吗? (如果是固定数字,当然容易多了)
标签: java generics java-8 functional-programming type-erasure