Java Generics return type issue
generics, java
Solution
To answer your edited question,
there's no way to do that without an explicit cast. So the simplest (yet brutal) solution would be:
public <T extends Result> T execute(Command<T> command) {
return (T) new LoginResult();
}
But this way you take the full responsibility for instantiating the right result for the right command, as the compiler won't help you any more.
The only thing that could help you instantiate things dynamically would be a reference to the actual `Class<T>`.
So if you add a method like `Class<T> getResultType()` to your command, you would be able to write:
return command.getResultType().newInstance(); // instead of new SpecificResult()
This of course implies that you have a default constructor in each `Result` implementation and so on...
A more OO friendly approach (no reflection) would be to let the command instantiate its own result (with a factory method `T instantiateResult()`):
return command.instantiateResult();
Problem
I have the following method: ``` public <T extends Result> T execute(Command<T> command) { return new LoginResult(); } ``` Here, `Result` is an interface, and the class `LoginResult` does implement this interface. However, I'm getting the error: Incompatible types, required: T, found: com.foo.LoginResult Yet if I change the method signature to: ``` public Result execute(Command<T> command) ``` Then the same return line works fine, without any error. What's the issue here? And how can I return `LoginResult` from this method? Edit: The reason I want to use generics, is so I can do something like the following: ``` Command<LoginResult> login = new Command<>(); LoginResult result = execute( login ); ```