Moje pytanie nie jest łatwe do wyjaśnienia za pomocą słów, na szczęście nie jest to zbyt trudne do wykazania. Tak więc pokrywa się ze mną:Jak prawidłowo połączyć generykę i dziedziczenie, aby uzyskać pożądany rezultat?
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;
}
});
}
}
Zasadniczo chcę rodzajową „proces” metoda dyktować rodzaj parametru rodzajowego obiektu Command. Celem jest umożliwienie ograniczenia różnych implementacji CommandProcessor do niektórych klas implementujących interfejs poleceń, a jednocześnie umożliwienie wywołania metody procesu dowolnej klasy, która implementuje interfejs CommandProcessor i zwrócenie obiektu typu określonego przez sparametryzowany obiekt polecenia. Nie jestem pewien, czy moje wyjaśnienie jest wystarczająco jasne, więc proszę dać mi znać, czy potrzebne są dalsze wyjaśnienia. Chyba pytanie brzmi: "Czy to w ogóle możliwe?" Jeśli odpowiedź brzmi "Nie", to co byłoby najlepszym obejściem (pomyślałem o sobie samemu, ale chciałbym trochę świeżych pomysłów).
Czy 'BasicCommand' nie powinien implementować' Command'? –
Touche, naprawione. Dziękujemy za złapanie tego! – Andrey