ParameterizedType
- getClass().getGenericSuperclass()
返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type,然后将其转换ParameterizedType。 - getActualTypeArguments()
返回表示此类型实际类型参数的 Type 对象的数组。[0]就是这个数组中第一个了。简而言之就是获得超类的泛型参数的实际类型。
Base Service
public abstract class BaseService<T> implements ServiceInterface<T> { private Class<T> clazz; /** * 实体管理器引用 * * @return EntityManager */ protected abstract EntityManager getEntityManager(); /** * DAO接口引用 * * @return DAOInterface<T> */ protected abstract DAOInterface<T> getDAOInterface(); /** * 构造函数反射泛型对象真实类型 */ @SuppressWarnings("unchecked") public BaseService() { // 获取当前new的对象的泛型父类 ParameterizedType pType = (ParameterizedType) this.getClass().getGenericSuperclass(); // 获取类型参数的真是值,就是泛型参数的个数; 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(); } }