This discussion is archived
2 Replies Latest reply: Mar 24, 2011 2:48 AM by 849958 RSS

Chaining tasks using generics

849958 Newbie
Currently Being Moderated
Hi everyone,

I am trying to create an API for chaining tasks.

First, I designed a very simple interface defining a task:

public interface Task<U, V> {
U execute(V input);
}

Where V is the input type and U the output type of the task.

What I whish to create is a Chain class that would chain a list of Tasks.

For instance, I would like to exexute: Task1<TypeA, TypeB> -> Task2<TypeB, TypeC> -> Task3<TypeC, TypeD>

This Chain class would thus be a Task<TypeA, TypeD>.

So I wrote this code, which does not compile :

public class Chain<U, V> implements Task<U, V>{
List<Task<?, ?>> taskList;

public Chain() {
taskList = new LinkedList<Task<?, ?>>();
}

@Override
public U execute(V input) {
V currentInput = input;
U output = null;
for (Task<?, ?> task : taskList) {
output = task.execute(currentInput); // Compile error because currentInput is of type V and output of type U
currentInput = output; // Compile error as well
}

return output;
}

// Other methods to add and remove tasks in the list

}

I do understand why it cannot compile but I have no idea how I could implement something that works and answers my problem.

Has anyone ever faced this kind of problem?

Kind regards,

Ben

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points