![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@Transactional public abstract class DAOSupport<T> implements DAO<T> { protected Class<T> clazz = GenericUtil.getGenericSuperClass(this.getClass()); @Resource protected SessionFactory sessionFactory; public T find( Integer id) { return (T)sessionFactory.getCurrentSession().get(clazz, id); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class GenericUtil { public static Class getGenericSuperClass( Class clazz) { Type type = clazz.getGenericSuperclass(); if(!(type instanceof ParameterizedType)){ throw new RuntimeException(); } ParameterizedType parameterizedType=(ParameterizedType)type; Type [] types = parameterizedType.getActualTypeArguments(); return (Class)types[0]; } }
java里貌似不能如.net typeof(T)来获取,hibernate居然也没有session.get<T>(object id)这样的方法。。。,而必须时session.get(clazz,object)这样,貌似就要像上面这样转个圈才能获取。