绝对有可能将其提取出来,
Class#getGenericSuperclass()因为它不是在运行时定义的,而是在编译时由定义的
FooDaoextends baseDao<Foo>。
这是一个启动示例,您可以如何在抽象类的构造函数中提取所需的泛型超类型,同时考虑子类的层次结构(以及
EntityManager在无需显式提供类型的情况下将其应用于泛型方法的实际用例)):
public abstract class baseDao<E extends baseEntity> { @PersistenceContext private EntityManager em; private Class<E> type; @SuppressWarnings("unchecked") // For the cast on Class<E>. public baseDao() { Type type = getClass().getGenericSuperclass(); while (!(type instanceof ParameterizedType) || ((ParameterizedType) type).getRawType() != baseDao.class) { if (type instanceof ParameterizedType) { type = ((Class<?>) ((ParameterizedType) type).getRawType()).getGenericSuperclass(); } else { type = ((Class<?>) type).getGenericSuperclass(); } } this.type = (Class<E>) ((ParameterizedType) type).getActualTypeArguments()[0]; } public E find(Long id) { return em.find(type, id); } public List<E> list() { return em.createQuery(String.format("SELECt e FROM %s e ORDER BY id", type.getSimpleName()), type).getResultList(); } // ...}


