我的問題不容易用單詞來解釋,幸運的是這並不難說明。所以,多多包涵:如何正確混合泛型和繼承以獲得期望的結果?
public interface Command<R>
{
public R execute();//parameter R is the type of object that will be returned as the result of the execution of this command
}
public abstract class BasicCommand<R> implements Command<R>
{
}
public interface CommandProcessor<C extends Command<?>>
{
public <R> R process(C<R> command);//this is my question... it's illegal to do, but you understand the idea behind it, right?
}
//constrain BasicCommandProcessor to commands that subclass BasicCommand
public class BasicCommandProcessor<C extends BasicCommand<?>> implements CommandProcessor<C>
{
//here, only subclasses of BasicCommand should be allowed as arguments but these
//BasicCommand object should be parameterized by R, like so: BasicCommand<R>
//so the method signature should really be
// public <R> R process(BasicCommand<R> command)
//which would break the inheritance if the interface's method signature was instead:
// public <R> R process(Command<R> command);
//I really hope this fully illustrates my conundrum
public <R> R process(C<R> command)
{
return command.execute();
}
}
public class CommandContext
{
public static void main(String... args)
{
BasicCommandProcessor<BasicCommand<?>> bcp = new BasicCommandProcessor<BasicCommand<?>>();
String textResult = bcp.execute(new BasicCommand<String>()
{
public String execute()
{
return "result";
}
});
Long numericResult = bcp.execute(new BasicCommand<Long>()
{
public Long execute()
{
return 123L;
}
});
}
}
基本上,我想一般的「過程」的方法來決定Command對象的泛型參數的類型。目標是能夠將CommandProcessor的不同實現限制爲實現Command接口的某些類,同時能夠調用任何實現了CommandProcessor接口的類的進程方法,並使其返回指定類型的對象參數化的Command對象。我不確定我的解釋是否足夠清楚,如果需要進一步解釋,請告訴我。我想,問題是「這樣做可能嗎?」如果答案是「否」,那麼最好的解決辦法是什麼(我自己想到一對夫婦,但我想要一些新想法)
不應該'BasicCommand'執行'Command'嗎? – 2010-06-12 19:27:46
Touche,固定。謝謝你接受! – Andrey 2010-06-12 19:31:41