Basically, I want the general method "process" to dictate the type of the general parameter of the command object.
This contradicts the notion of defining a command as a type parameter for an application type: when creating an instance of CommandProcessor for C , an actual type can be provided, for example, Command<String> . It would even be possible to provide a non-generic type, e.g.
class Foo implements Command<String> { ... }
What will C<R> mean then? Foo<R> ? Command<String><R> ? Command<R> ?
So what are your options? If the CommandProcessor should only work with a specific return type, you can do the following:
class CommandProcessor<R, C extends Command<R>> { R process(C command); } class FancyCommandProcessor<R, C extends FancyCommand<R>> extends CommandProcessor<R,C> { }
However, I suspect that you want the CommandProcessor to work with all types of commands. This in itself will not be a problem, just declare:
<R> R process(FancyCommand<R> command);
If, however, you also need a subtype between CommandProcessors for different families of commands so that you can override the process , you go beyond the expressiveness of Java generics. In particular, you will need either the equivalent of C ++ template type parameters (which allow you to pass a template as an actual type argument), or the ability to capture a command type parameter taking into account the actual type argument, which, as you know, extends Command, Java does not support .
meriton
source share