遗忘海岸

江湖程序员 -Feiph(LM战士)

导航

java类的泛型DAO

@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);
    }
}
View Code
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];
    }

}
View Code

 

java里貌似不能如.net typeof(T)来获取,hibernate居然也没有session.get<T>(object id)这样的方法。。。,而必须时session.get(clazz,object)这样,貌似就要像上面这样转个圈才能获取。

posted on 2013-08-08 08:02  遗忘海岸  阅读(574)  评论(0编辑  收藏  举报