似乎我在 Java 泛型方面遗漏了一些东西,因为我认为有些东西很简单,但在我看来这是无法完成的。也许你可以帮助...
这是场景:我正在使用简单的 CRUD 操作编写通用抽象 DAO,因此我的应用程序的每个特定 DAO 都可以免费使用它:
public abstract DefaultDAO<T,V> {
private EntityManager manager;
public BaseDAO(EntityManager em) {
this.manager = em;
}
public void create(T entity) {
manager.persist(entity);
}
// You know the others...
public T read(V pk) {
// Now, here is the problem.
// EntityManager signature is: public <T> T find(Class<T> entityClass, Object primaryKey);
// So I must provide the type of the object this method will be returning and
// the primary key.
// resulting object will be T typed and pk type is V type (although is not needed to type it since the method expects an Object)
// So... I expected to be allowed to do something like this
return manager.find(T, pk); // But it's not allowed to use T here. T is not an instance
}
}
现在我会去实现一个特定的 DAO:
public PersonDAO extends DefaultDAO<PersonEntity, Long> {
public PersonDAO(EntityManager em) {
super(em);
}
// CRUD methods are inherited
}
我的 DAO 的客户端代码是:
EntityManager manager = ...
PersonDAO dao = new PersonDAO(manager);
Long pk = .....
PersonEntity person = dao.find(pk); // DAO would return a PersonEntity
当客户端执行代码时,BaseDAO 知道它必须返回的实体类型以及该实体的主键类型,因为我将它设置在特定的 dao 上,但我不知道如何正确编写 read() 方法。
希望你能帮忙。非常感谢!