首页 > 代码库 > Dao泛型设计和反射反型

Dao泛型设计和反射反型

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

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

 1 package cn.itcast.web.generic;
 2 
 3 import java.lang.reflect.ParameterizedType;
 4 import java.lang.reflect.Type;
 5 import org.apache.commons.dbutils.QueryRunner;
 6 import org.apache.commons.dbutils.handlers.BeanHandler;
 7 import cn.itcast.web.util.JdbcUtil;
 8 
 9 //泛型父类
10 public class BaseDao<T> {
11     private String tableName;
12     private Class clazz;
13     public BaseDao(){
14         //BaseDao<Student>叫参数化类型,ParameterizedType对象
15         //获取该类的字节码对象
16         Class baseDaoClass = this.getClass();
17         //获取Type接口
18         Type type = baseDaoClass.getGenericSuperclass();
19         //将Type接口强转成ParameterizedType
20         ParameterizedType pt = (ParameterizedType) type;
21         //获取<Student>类型
22         Type[] types = pt.getActualTypeArguments();
23         //获取第一个实际参数
24         this.clazz = (Class) types[0];
25         //根据字节码转成表名
26         int index = this.clazz.getName().lastIndexOf(".");
27         this.tableName = this.clazz.getName().substring(index+1).toLowerCase();
       System.out.println(clazz.getName());
28     }
29     /*
30     public BaseDao(String tableName, Class clazz) {
31         this.tableName = tableName;
32         this.clazz = clazz;
33     }
34     */
35     //根据ID查询对象
36     public T findById(Integer id) throws Exception{
37         T t = null;
38         QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
39         String sql = "select * from " + tableName + " where id = ?";
40         Object[] params = {id};
41         t = (T) runner.query(sql,new BeanHandler(clazz),params);
42         return t;
43     }
44 }
1 //子类
2 public class StudentDao extends BaseDao<Student>{
3     /*
4     public StudentDao(String tableName, Class clazz) {
5         super(tableName, clazz);
6     }
7     */
8 }
View Code
 1 package cn.itcast.web.generic;
 2 
 3 import cn.itcast.web.domain.Teacher;
 4 
 5 //子类
 6 public class TeacherDao extends BaseDao<Teacher>{
 7     /*
 8     public TeacherDao(String tableName, Class clazz) {
 9         super(tableName, clazz);
10     }
11     */
12 }
View Code
1     @Test
2     public void test() {
3         TeacherDao tdao=new TeacherDao();
4         StudentDao sdao=new StudentDao();
5     }