I have class:
public class GenericDAO<T, ID extends Serializable> {
private final EntityManager em;
private final Class<T> entityClass;
public GenericDAO(EntityManager em) {
this.em = em;
ParameterizedType genericSuperClass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<T>) genericSuperClass.getActualTypeArguments()[0];
}
}
If I extend this class all works fine. Now I want to use this class directly (see code belove, CRUDBean is implementation of CRUDService) – it is necessary to rewrite constructor to get particular class.
@Remote(CRUDService.class)
@Stateless
public class CRUDBean<T extends EntityBase> implements CRUDService<T> {
@PersistenceContext
private EntityManager entityManager;
@Override
public long size(String whereClause, Map<String, Object> whereParameters) {
return new GenericDAO<T, Long>(entityManager).size(whereClause, whereParameters);
}
}
How to write such generics service?
Yes, you would need to create a separate constructor.
Your current constructor assumes that
thisis an instance of a subclass ofGenericDAO, and it uses that fact to get the type parameter for you throughgetClass().getGenericSuperclass().getActualTypeArguments().To use
GenericDAOdirectly, you should create aGenericDAOconstructor which takes the entity class (whatever typeTreally is) as an argument. Then provide the entity class inCRUDBean.size()or wherever you need to instantiate yourGenericDAO.If you don’t have the actual class available in
CRUDBean, have three choices:CRUDBeanconstructor which takes the entity class as an argument.size()which takes the entity class as an argument.GenericDAOconstructor to get it, but withgetGenericInterfaces()instead.