我正在尝试使用泛型实现命令模式的非常简单的实现
public abstract class Command {
}
public interface CommandHandler<H extends Command> {
boolean isActive();
void execute( H command );
}
public class CommandExecutionServiceImpl implements CommandExecutionService {
private Map< Class<Command>,CommandHandler<Command>> commandMap;
public CommandExecutionServiceImpl(){
commandMap = new HashMap<Class<Command>, CommandHandler<Command>>();
}
@Override
public void executeCommand(Command command) {
CommandHandler<Command> handler = commandMap.get(command.getClass());
handler.execute(command);
}
@Override
public boolean isActive(Command command) {
return false;
}
@Override
public <H extends Command> void addCommandHandler(Class<H> commandClass, CommandHandler<H> handler) {
commandMap.put( commandClass, handler );
}
编译器失败
编译失败CommandExecutionServiceImpl.java:[36,12] put(java.lang.Class,CommandHandler) in java.util.Map,CommandHandler> 不能应用于(java.lang.Class,CommandHandler)
我不明白为什么编译器无法推断 commandMap.put(commandClass, handler); 的类型
任何帮助,将不胜感激。