1 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
我認(rèn)為你必須編寫返回類型取決于Function參數(shù)的方法:
class InputConverter<T> {
private final T value;
public InputConverter(T value) {
this.value = value;
}
public <R> R convertBy(Function<T, R> function){
return function.apply(value);
}
}
然后您可以Function使用標(biāo)準(zhǔn)方法將參數(shù)組合compose起來andThen:
final String fname = "fname_value"
InputConverter<String> inputConverter = new InputConverter<>(fname);
Function<String, List<String>> valueToListFunction = Arrays::asList;
Function<List<String>, String> firstValueFunction = l -> l.get(0);
List<String> strings = inputConverter.convertBy(valueToListFunction);//[fname_value]
String firstValue = inputConverter.convertBy(
valueToListFunction
.andThen(firstValueFunction)
);
您也可以使用其他標(biāo)準(zhǔn)FunctionalInterfaces,例如UnaryOperator:
UnaryOperator<String> firstChangeFunction = arg -> arg.concat(" + first");
UnaryOperator<String> secondChangeFunction = arg -> arg.concat(" + second");
String firstValue = inputConverter.convertBy(
valueToListFunction
.andThen(firstValueFunction)
.andThen(secondChangeFunction)
.compose(firstChangeFunction)
); // sout: fname_value + first + second
或者自己寫。
添加回答
舉報(bào)