这就是我想做的事情:
我希望有一个抽象类Operation
实现Function
接口,然后有像OpA
继承它的子类。 Operation
是从Function
到Integer
的Integer
,我希望能够使用Function.compose
和Function.andThen
来组成OpA
s。在代码中:
public abstract class Operation implements Function<Integer, Integer>
{
// ...
}
public class OpA extends Operation
{
// ...
}
public class Main
{
public static void main(String[] args)
{
OpA a = new OpA();
OpA b = new OpA();
// vvv Problem here vvv
Operation compose = (Operation) a.andThen(b);
}
}
问题是,尽管a.andThen(b)
是从Function
到Integer
的Integer
,我不能把它投到Operation
。在运行时抛出java.lang.ClassCastException
:
Caused by: java.lang.ClassCastException: java.util.function.Function$$Lambda$56/1571051291 cannot be cast to operation.Operation
at application.Main.main(Main.java:25)
说实话,我并不是真的希望它能像那样开始工作,但出于我的目的,我真的需要组合函数成为Operation
。所以对于我的问题,我要求一种方法来使函数组合返回一个与Operation
类型兼容的对象。任何有效的方法都很好:如果有必要的话,我愿意写自己的composed
和andThen
功能(但我不知道怎么做),虽然总是很受欢迎。
好吧,如果你想要实现一个Sum
,可以这样做:
static class Sum extends Operation {
@Override
public Integer apply(Integer x) {
return x + 1;
}
public Operation andThen(Operation after) {
return new Operation() {
@Override
public Integer apply(Integer x) {
return after.apply(Sum.this.apply(x));
}
};
}
}
打电话给:
Sum a = new Sum();
Sum b = new Sum();
Operation composed = a.andThen(b);
System.out.println(composed.apply(2)); // 4