Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I do this Generic thing?
    text
    copied!<p>It seems I'm missing something with Java Generics because something I think is simple, it appears to me that can´t be done. Maybe you can help...</p> <p>This is the scenario: I'm coding a generic abstract DAO with simple CRUD operation so every specific DAO of my application can have it for free:</p> <pre><code>public abstract DefaultDAO&lt;T,V&gt; { 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 &lt;T&gt; T find(Class&lt;T&gt; 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 } } </code></pre> <p>Now I would go and implement an specific DAO:</p> <pre><code>public PersonDAO extends DefaultDAO&lt;PersonEntity, Long&gt; { public PersonDAO(EntityManager em) { super(em); } // CRUD methods are inherited } </code></pre> <p>And client code for my DAO would be:</p> <pre><code>EntityManager manager = ... PersonDAO dao = new PersonDAO(manager); Long pk = ..... PersonEntity person = dao.find(pk); // DAO would return a PersonEntity </code></pre> <p>When client executes code, BaseDAO knows the type of entity it must return and the type of the primary key of that entity because I set it on the specific dao, but I don't know how to code the read() method correctly.</p> <p>Hope you can help. Thanks a lot!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload