Dao泛型设计和反射反型

时间:2023-03-10 02:25:50
Dao泛型设计和反射反型

(1)DAO泛型设计:当二哥或多个类中有类似的方法时,可以将这些累死的方法提出到类中,形式一个泛型父类

(2)反射反型:在泛型父类中获取子类的具体类型的过程,叫反射反型

 package cn.itcast.web.generic;

 import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import cn.itcast.web.util.JdbcUtil; //泛型父类
public class BaseDao<T> {
private String tableName;
private Class clazz;
public BaseDao(){
//BaseDao<Student>叫参数化类型,ParameterizedType对象
//获取该类的字节码对象
Class baseDaoClass = this.getClass();
//获取Type接口
Type type = baseDaoClass.getGenericSuperclass();
//将Type接口强转成ParameterizedType
ParameterizedType pt = (ParameterizedType) type;
//获取<Student>类型
Type[] types = pt.getActualTypeArguments();
//获取第一个实际参数
this.clazz = (Class) types[0];
//根据字节码转成表名
int index = this.clazz.getName().lastIndexOf(".");
this.tableName = this.clazz.getName().substring(index+1).toLowerCase();
       System.out.println(clazz.getName());
}
/*
public BaseDao(String tableName, Class clazz) {
this.tableName = tableName;
this.clazz = clazz;
}
*/
//根据ID查询对象
public T findById(Integer id) throws Exception{
T t = null;
QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
String sql = "select * from " + tableName + " where id = ?";
Object[] params = {id};
t = (T) runner.query(sql,new BeanHandler(clazz),params);
return t;
}
}
 //子类
public class StudentDao extends BaseDao<Student>{
/*
public StudentDao(String tableName, Class clazz) {
super(tableName, clazz);
}
*/
}
 package cn.itcast.web.generic;

 import cn.itcast.web.domain.Teacher;

 //子类
public class TeacherDao extends BaseDao<Teacher>{
/*
public TeacherDao(String tableName, Class clazz) {
super(tableName, clazz);
}
*/
}
     @Test
public void test() {
TeacherDao tdao=new TeacherDao();
StudentDao sdao=new StudentDao();
}