据我所知,您正在尝试做这样的事情:
public static void main(String... args){
List<Object> lambdas = Arrays.asList(
(IntBinaryOperator) (int a, int b) -> a + b,
(DoubleToIntFunction) (double d) -> (int)(d * 2)
);
for(int i=0;i<args.length;i++){
// Apply lambdas.get(i) to args[i]
}
}
不过,这条评论很重要;你将如何实现它?
您可以在每一轮中检查类型:
for(int i=0;i<args.length;i++){
if(lambdas.get(i) instanceof IntBinaryOperator){
processedArgs[i] =
((IntBinaryOperator) lambdas.get(i)).applyAsInt(MAGIC_NUMBER, Integer.parseInt(args[i]));
}else{
// All your other cases (may take a while)
}
}
验证每一种可能的类型是一件非常痛苦的事情,如果它依赖于位置,那么它无论如何只会运行一次,所以它是矫枉过正的。
我的建议取决于这是静态的(您的代码只在一组特定的参数上运行)还是动态的(它需要在各种参数上运行)。对于静态代码,我只应用没有循环的 lambda:
public static void main(String... args){
processedArgs = new int[args.length];
IntBinaryOperator op1 = (int a, int b) -> a + b;
DoubleToIntFunction op2 = (double d) -> (int)(d * 2);
processedArgs[0] = op1.applyAsInt(MAGIC_NUMBER, Integer.parseInt(args[0]));
processedArgs[1] = op2.applyAsInt(Double.parseDouble(args[1]));
}
对于动态解决方案,我建议切换到单一功能界面。我会采用最大要求并在不需要的地方填写虚拟值:
public static void main(String... args){
processedArgs = new int[args.length];
List<DoubleBinaryOperator> ops = Arrays.asList(
(a, b) -> a + b,
(d, ignore) -> (d * 2)
);
for(int i=0;i<args.length;i++){
processedArgs[i] = (int)ops.get(i).applyAsDouble(Double.parseDouble(args[i]), MAGIC_NUMBER);
}
}
或者,如果您可以简化您的 lambda,最好:
public static void main(String... args){
processedArgs = new int[args.length];
List<DoubleToIntFunction> ops = Arrays.asList(
(d) -> (int)(d + MAGIC_NUMBER),
(d) -> (int)(d * 2)
);
for(int i=0;i<args.length;i++){
processedArgs[i] = ops.get(i).applyAsInt(Double.parseDouble(args[i]));
}
}
我觉得您的解决方案最终比其中任何一个都简单。只是想帮助您指出正确的方向。