1.BaseDao<T>
package org.hzy.dao; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class BaseDao<T extends EntitysSuper> { //参数可以是多个<T,K> static Configuration config = new Configuration().configure(); static SessionFactory fac = config.buildSessionFactory(); private Class entityclass; public Session getSession() { return fac.getCurrentSession(); } public BaseDao() { // TODO Auto-generated constructor stub this.entityclass = getParameterizedType(this.getClass()); } protected Class getParameterizedType(Class clazz) { //返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。 Type ty = clazz.getGenericSuperclass(); // 得到传入进来类的父类型 //BaseDao<Dept>--org.hzy.dao.BaseDao<org.hzy.entity.Dept> // System.out.println(ty); Type[] types=null; if (ty instanceof ParameterizedType) { //注意此处ty必须是有泛型参数 , 得到当前类型的泛型 <Dept>--class org.hzy.entity.Dept types= ((ParameterizedType) ty).getActualTypeArguments(); }else{ try { throw new Exception("not find ParameterizedType!"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // System.out.println(types[0]); // Type t=((ParameterizedType)ty).getRawType();//得到声明这个类型的类或者接口 return (Class) types[0]; } public T get_object(Integer id) { return (T) this.getSession().get(entityclass, id); } }2.测试,通过不同的类则返回你这个类的类型: public class DeptImpl extends BaseDao<Dept>{ public static void main(String[] args) { DeptImpl de=new DeptImpl(); Transaction t=de.getSession().beginTransaction(); System.out.println(de.get_object(10)); t.commit(); } }
public class EmpImpl extends BaseDao<Emp>{ public static void main(String[] args) { EmpImpl em=new EmpImpl(); Transaction t=em.getSession().beginTransaction(); Emp emp=em.get_object(7369); System.out.println(emp.getEname()); t.commit(); } }
通过使用泛型T减少Dao的冗余代码,当T继承某个对象时(T extends EntityDao)限制了参数类型必须继承该对象(EntityDao),并且ClassT必须要有泛型参数(DeptDaoImpl extends ClassT<Dept>),否则转换失败。