package org.han.classt;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.han.entity.EntityDao;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class ClassT<T extends EntityDao> {//ClassT<T extends EntityDao,K>多个参数
private Class entityClass;
public ClassT() {
super();
// TODO Auto-generated constructor stub
entityClass=getParameterizedType(this.getClass());
}
/*
* 获得当前类的Class
*/
private Class getParameterizedType(Class c){
Type type=c.getGenericSuperclass();//返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。
ParameterizedType parametType=null;
if (type instanceof ParameterizedType) {
parametType=(ParameterizedType)type;//注意此处type必须是有泛型参数
}else{
try {
throw new Exception("not find ParameterizedType!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Type[] types=parametType.getActualTypeArguments();//返回表示此类型实际类型参数的 Type 对象的数组
return (Class)types[0];
}
/*
* 通用通过ID获得实体类的方法
*/
public T getEntityById(Integer primaryKey){
Session sess=new Configuration().configure("main.xml").buildSessionFactory().getCurrentSession();
sess.beginTransaction();
T t=(T)sess.get(this.entityClass, primaryKey);
sess.getTransaction().commit();
return t;
}
}
Dao代码:
package org.han.dao;
import org.han.classt.ClassT;
import org.han.entity.Emp;
public class EmpDaoImpl extends ClassT<Emp> {
}
package org.han.dao;
import org.han.classt.ClassT;
import org.han.entity.Dept;
public class DeptDaoImpl extends ClassT<Dept> {
}
Emp、Dept直接使用ClassT的getEntityById(Integer id)获得对应的实体
public static void main(String[] args) {
// TODO Auto-generated method stub
DeptDaoImpl deptDao=new DeptDaoImpl();
Dept d=deptDao.getEntityById(10);
System.out.println(d.getDname());
EmpDaoImpl empDao=new EmpDaoImpl();
Emp e=(Emp)empDao.getEntityById(7369);
System.out.println(e);
}
通过使用泛型T减少Dao的冗余代码,当T继承某个对象时(T extends EntityDao)限制了参数类型必须继承该对象(EntityDao),并且ClassT必须要有泛型参数(DeptDaoImpl extends ClassT<Dept>),否则转换失败。