SmokeIT
SmokeIT

Reputation: 103

Java - generic parameter can't be resolved

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?

Upvotes: 9

Views: 1896

Answers (1)

sp00m
sp00m

Reputation: 48827

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

Upvotes: 10

Related Questions