- 最近使用泛型听频繁的,先简单的总结下,慢慢更新。
问题:现在有两个dao里面有相同的方法,只是查的表和返回的类型不一样,我们写一个BaseDao,写公用的方法,让其他的dao来继承。这里的前提是实体类名和数据库表名一样。
//两个dao继承BaseDao,并指定自己类使用的实体。
1public class AdminDao extends BaseDao<Admin> {}
2 public class AccountDao extends BaseDao<Account> {}
1 /**
2 * 所有dao的公用的方法,都在这里实现
3 * 4 *
5 */
6 public class BaseDao<T>{
7
8 // 保存当前运行类的参数化类型中的实际的类型
9 private Class clazz;
10 // 表名
11 private String tableName;
12
13
14
15 // 构造函数: 1. 获取当前运行类的参数化类型; 2. 获取参数化类型中实际类型的定义(class)
16 public BaseDao(){
17 // this 表示当前运行类 (AccountDao/AdminDao)
18 // this.getClass() 当前运行类的字节码(AccountDao.class/AdminDao.class)
19 // this.getClass().getGenericSuperclass(); 当前运行类的父类,即为BaseDao<Account>
20 // 其实就是“参数化类型”, ParameterizedType
21 Type type = this.getClass().getGenericSuperclass();
22 // 强制转换为“参数化类型” 【BaseDao<Account>】
23 ParameterizedType pt = (ParameterizedType) type;
24 // 获取参数化类型中,实际类型的定义 【new Type[]{Account.class}】
25 Type types[] = pt.getActualTypeArguments();
26 // 获取数据的第一个元素:Accout.class
27 clazz = (Class) types[0];
28 // 表名 (与类名一样,只要获取类名就可以)
29 tableName = clazz.getSimpleName();
30 }
31
32
33 /**
34 * 主键查询
35 * @param id 主键值
36 * @return 返回封装后的对象
37 */
38 public T findById(int id){
39 /*
40 * 1. 知道封装的对象的类型
41 * 2. 表名【表名与对象名称一样, 且主键都为id】
42 *
43 * 即,
44 * ---》得到当前运行类继承的父类 BaseDao<Account>
45 * ----》 得到Account.class
46 */
47
48 String sql = "select * from " + tableName + " where id=? ";
49 try {
50 return JdbcUtils.getQuerrRunner().query(sql, new BeanHandler<T>(clazz), id);
51 } catch (SQLException e) {
52 throw new RuntimeException(e);
53 }
54 }
55
56
57 /**
58 * 查询全部
59 * @return
60 */
61 public List<T> getAll(){
62 String sql = "select * from " + tableName ;
63 try {
64 return JdbcUtils.getQuerrRunner().query(sql, new BeanListHandler<T>(clazz));
65 } catch (SQLException e) {
66 throw new RuntimeException(e);
67 }
68 }
69 }
- 代码中的一些知识点:
反射泛型涉及API:
Student 类型的表示
Id name
ParameterizedType 参数化类型的表示
ArrayList<String>();
Type 接口,任何类型默认的接口!
包括: 引用类型、原始类型、参数化类型
List<String> list = new ArrayList<String>();
泛型集合: list
集合元素定义:new ArrayList<String>(); 中的String
参数化类型: ParameterizedType
即:“ArrayList<String> ” 为参数化类型