Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics return type issue

Tags:

java

generics

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 );
like image 205
Ali Avatar asked Feb 11 '14 14:02

Ali


People also ask

Can Java return type be generic?

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 ) { ... } }

How do generics ensure type safety?

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.

Why generics are not supported to primitive data type?

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.


1 Answers

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).

like image 191
SimonC Avatar answered Sep 30 '22 20:09

SimonC