Doubt with Generics in Java

Asked

Viewed 34 times

0

I have a class that uses generic type

public abstract class AbstractDAO <T extends Entidade>{
    //corpo da classe
}

At some point I need to know the class of T, the compiler does not accept to use T.class.

public void remover(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            T entidade;
            try {
                //Nesse momento preciso saber a classe de T.
                entidade = em.getReference(T.class, id);
                entidade.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("A entidade com id "+id+" não existe", enfe);
            }
            em.remove(entidade);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

How can I fix this?

  • At what point? Show that you need it.

  • Hello. I marked the answer as duplicate because @Anthonyaccioly’s answer perfectly answers that question. Just ask getClass().getGenericSuperclass()).getActualTypeArguments()[0]to catch the guy.

  • Thank you, that’s right, it worked.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.