1

I have a generic method that gets a return type (ReturnT) by type interfering from the input parameter type (Command<ReturnT>). Now I would like to add an (upper) bound to the input parameter type, such that it has to extend a type parameter given as class type parameter.

In the example below I would like to add something like CommandT extends BaseCommandT (while the CommandT extends Command<ReturnT> remains).

My first try CommandT extends BaseCommandT&Command<ReturnT> results in: The interface Command cannot be implemented more than once with different arguments: TestGenerics.Command<ReturnT> and TestGenerics.Command<?>

Is this somehow possible?

interface Command<ReturnT> {}
interface CommandExecutor<CommandT extends Command<ReturnT>,ReturnT>{
   ReturnT execute(CommandT cmd);
}

class ExecutorRegistry<BaseCommandT extends Command<?>> {
  public <ReturnT, CommandT extends Command<ReturnT>> ReturnT execute(CommandT cmd){
    return ((CommandExecutor<Command<ReturnT>,ReturnT>)executors.get(cmd.getClass())).execute(cmd);
  }
}

For completeness, the following field and method are also part of my ExecutorRegistry class:

Map<Class<? extends BaseCommandT>,CommandExecutor<?,?>> executors = new HashMap<>();
public void register(Class<? extends BaseCommandT> cls, CommandExecutor<?, ?> executor){
    executors.put(cls, executor);
}    
Rapsack
  • 29
  • 3
  • 1
    Don't use full uppercase names for classes, stick to the Java naming conventions of `ClassName`. – user1803551 Oct 19 '15 at 21:39
  • 1
    ...or in the case of type parameters, single letter names. – biziclop Oct 19 '15 at 21:42
  • I like having descriptive names (not single letters) and being able to easily distinguish between type parameters and class names (OK, the code formater should do this). So I use the google code convetion (as discussed here: http://stackoverflow.com/questions/2900881/generic-type-parameter-naming-convention-for-java-with-multiple-chars ) and replace COMMAND, BASECOMMAND and RETURN with the according names. – Rapsack Oct 19 '15 at 22:06

0 Answers0