I\'ve been struggling with the following problem. I have a series of function objects, each with it\'s own input and output types defined via generic type arguments in java. I w
Here's a way to do it. The run method is not typesafe, but given that the only way to append a pipe is to do it in a type-safe way, the whole chain is type-safe.
public class Chain {
private List> pipes;
private Chain() {
}
public static Chain start(Pipe pipe) {
Chain chain = new Chain();
chain.pipes = Collections.>singletonList(pipe);;
return chain;
}
public Chain append(Pipe pipe) {
Chain chain = new Chain();
chain.pipes = new ArrayList>(pipes);
chain.pipes.add(pipe);
return chain;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public T run(S s) {
Object source = s;
Object target = null;
for (Pipe p : pipes) {
target = p.transform(source);
source = target;
}
return (T) target;
}
public static void main(String[] args) {
Pipe pipe1 = new Pipe() {
@Override
public Integer transform(String s) {
return Integer.valueOf(s);
}
};
Pipe pipe2 = new Pipe() {
@Override
public Long transform(Integer s) {
return s.longValue();
}
};
Pipe pipe3 = new Pipe() {
@Override
public BigInteger transform(Long s) {
return new BigInteger(s.toString());
}
};
Chain chain = Chain.start(pipe1).append(pipe2).append(pipe3);
BigInteger result = chain.run("12");
System.out.println(result);
}
}