java类的泛型DAO

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
java类的泛型DAO
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)这样,貌似就要像上面这样转个圈才能获取。

你可能感兴趣的:(java)