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 );
So methods of generic or nongeneric classes can use generic types as argument and return types as well. Here are examples of those usages: // Not generic methods class GenericClass < T > { // method using generic class parameter type public void T cache ( T entry ) { ... } }
Generics were added to Java to ensure type safety. And to ensure that generics won't cause overhead at runtime, the compiler applies a process called type erasure on generics at compile time. Type erasure removes all type parameters and replaces them with their bounds or with Object if the type parameter is unbounded.
Type safety is verified at compile time, and runtime is unfettered by the generic type system. In turn, this imposed the restriction that generics could only work over reference types, since Object is the most general type available, and it does not extend to primitive types.
You can't do this because the compiler can't confirm that LoginResult
is of type T
, since it's inferred at the call site (i.e. the caller decides which type parameter will be used).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With