Class<T> 泛型T简化Dao

2014-11-24 07:56:14 · 作者: · 浏览: 0

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 {//ClassT多个参数

protected Class entityClass;

public ClassT() {
super();
// TODO Auto-generated constructor stub
entityClass=getParameterizedType(this.getClass());
}
/*
* 获得当前类的Class
*/
public 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代码:
[java]
package org.han.dao;

import org.han.classt.ClassT;
import org.han.entity.Emp;

public class EmpDaoImpl extends ClassT {

}

[java]
package org.han.dao;


import org.han.classt.ClassT;
import org.han.entity.Dept;

public class DeptDaoImpl extends ClassT {

}
Emp、Dept直接使用ClassT的getEntityById(Integer id)获得对应的实体
[java]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),否则转换失败。



摘自 hanzhou4519