Generic Java class of another generic class

I have a base general class representing all the objects of my model that have an identifier of any type:

public abstract class IdObject<T> {
    private T    id;
    public  T    getId()     { return this.id; }
    public  void setId(T id) { this.id = id;   }
}

Then I have a superinterface representing the DAO for these IdObjects:

public interface IdObjectDAO<T extends IdObject<U>> {
    public T getObjectById(U id);
}

but I get a compiler error "U cannot be resolved to type". If I changed the interface definition, follow these steps:

public interface IdObjectDAO<T extends IdObject<U extends Object>> {...}

I get a syntax error on the token syntax extends, "expected". The only way to define an interface without compiler errors:

public interface IdObjectDAO<T extends IdObject<? extends Object>> {...}

but then I have no type alias (U) for the method public T getObjectId(U id). The only solution I found to solve it is to use 2 types of parameters:

public interface IdObjectDAO<T extends IdObject<U>, U> {...}

, DAO:

public class     Person    extends IdObject<Integer> {...}
public interface PersonDAO extends IdObjectDAO<Person, Integer> {...}
                                                     ^^^^^^^^^ <== avoid this

- IdObjectDAO?

!

+4
1

, , .

public T getObjectById(U id);

T, U. U IdObject<U>, , , .

T , ( ) , , :

1) Lose:

public interface IdObjectDAO<T extends IdObject<?>> {
    public T getObjectById(Object id);
}

equals U,

id.equals(t.getId());

T T.

2) T:

public interface IdObjectDAO<T extends IdObject<?>> {
    public T getObjectBySample(T sample);
}

:

Integer id = 5;
Person sample = new Person(id);
Person object = personDao.getObjectBySample(sample);
+1

Source: https://habr.com/ru/post/1544306/


All Articles