Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - generic parameter can't be resolved

Tags:

java

generics

I'm writing a generic Dao interface and I have encountered some problems.

I have the following generic Entity interface

public interface Entity<T> {

    T getId();

    //more code
}

So the generic parameter is supposed to represent the id of the entity. And now I want to write a generic Dao initerface like this

public interface Dao<T extends Entity<E>> {

    //more code

    T find(E id); 

}

To be able to call

T find(E id)

Instead of having to call

T find(Object id)

which isn't typesafe.

Unfortunately the compiler doesn't seem to be able to resolve the E in

Dao<T extends Entity<E>>

Do any of you know if there is a workaround to this problem, or is it just impossible to do in Java?

like image 245
SmokeIT Avatar asked Jun 07 '13 07:06

SmokeIT


1 Answers

You have to pass the primary key as parameter too:

public interface Dao<K, T extends Entity<K>>

The pk usually is serializable, so you can improve the above signature:

public interface Dao<K extends Serializable, T extends Entity<K>>

And:

public interface Entity<K extends Serializable>

Then:

public class UserDao implements Dao<Integer, User> {
}
like image 62
sp00m Avatar answered Oct 20 '22 14:10

sp00m