So I want to implements the Chain of Responsibility but use generics, with an upper bound.
public abstract class Handler<C extends Command> {
private Handler<? extends Command> successor;
public Handler(Handler<? extends Command> successor) {
this.successor = successor;
}
public final String handle(C cmd) {
if (canHandle(cmd)) {
return doHandle(cmd);
} else {
// The method doHandle(capture#3-of ? extends Command) in the type Handler<capture#3-of ? extends Command>
// is not applicable for the arguments (C)
return successor.doHandle(cmd);
}
}
protected abstract boolean canHandle(C cmd);
protected abstract String doHandle(C cmd);
}
abstract class Command {
public String getParamBase() {
return "base";
}
}
class CommandTypeOne extends Command {
public String getTypeOneParam() {
return "ParamTypeOne";
}
}
class CommandTypeTwo extends Command {
public String getTypeTwoParam() {
return "ParamTypeTwo";
}
}
Sure I could have the class non-generic, and have Command as parameter everywhere, and that would work. But I don't want to use casting in the doHandle method to pass to the corresponding subtype of Command. I want to have a Handler for each of the subtypes, generic, and just chain them.
The issue I get is: The method doHandle(capture#3-of ? extends Command) in the type Handler is not applicable for the arguments (C)
Why if C extends Command?