ParameterizedType
- getClass().getGenericSuperclass()
returns the Type representing the immediate superclass of the entity (class, interface, primitive type, or void) represented by this Class, then converts it to ParameterizedType. - getActualTypeArguments()
returns an array of Type objects representing the actual type arguments of this type. [0] is the first one in this array. In short, get the actual type of the superclass's generic parameter.
Base Service
public abstract class BaseService<T> implements ServiceInterface<T> { private Class<T> clazz; /** * Entity manager reference * * @return EntityManager */ protected abstract EntityManager getEntityManager(); /** * DAO interface reference * * @return DAOInterface<T> */ protected abstract DAOInterface<T> getDAOInterface(); /** * The constructor reflects the real type of the generic object */ @SuppressWarnings( "unchecked" ) public BaseService() { // Get the generic parent class of the current new object ParameterizedType pType = (ParameterizedType) this .getClass().getGenericSuperclass(); // Get the true value of the type parameter , is the number of generic parameters; this .clazz = (Class<T>) pType.getActualTypeArguments()[0 ]; } @Override public T find(String id) throws Exception { return getEntityManager().find(clazz, id); } @Override public T save(T t) throws Exception { T save = getDAOInterface().save(t); return save; } @Override public void update(T t) throws Exception { getEntityManager().merge(t); } @Override public void del(String id) throws Exception { T t = getEntityManager().find(clazz, id); if (t != null) { getEntityManager().remove(t); } } @Override public List<T> findAll() throws Exception { return getDAOInterface().findAll(); } }