在做SSH的Dao优化的时候,老师提到了反射类型优化Dao 里面有些东西不明白,查了API 做一些整理
两个类 首先第一个类是BaseDao
<span style="font-size:18px;">public class BaseDao<T> implements IBaseDao<T> {
// 当前操作的实际的Bean类型
private Class<T> clazz;
//获取类名称
private String className;
// 反射泛型
@SuppressWarnings("unchecked")
public BaseDao() {
System.out.println(this.getClass());</span>
<span style="font-size:18px;"><span style="white-space:pre"> </span>//得到父类</span>
<span style="font-size:18px;"> Type type = this.getClass().getGenericSuperclass();
System.out.println(type);
//转换为参数化类型
ParameterizedType pt = (ParameterizedType) type;
System.out.println(pt);
//得到实际类型
Type types[] = pt.getActualTypeArguments();
//获取实际类型
clazz = (Class<T>) types[0];
System.out.println(clazz);
className = clazz.getSimpleName(); //例如Employee
System.out.println(className);
}</span>
另外一个类是ZhiDao 继承前面的BaseDao
<span style="font-size:18px;"> public static void main(String[] args) {
ZhigeDao zhi = new ZhigeDao();
}</span>
打印结果与名词解释:
class cn.zhige.dao.impl.ZhigeDao //this.class
cn.zhige.dao.impl.test<cn.zhige.dao.impl.ZhigeDao> //this.getClass().getGenericSuperclass();得到父类 要转化为参数化类型操作
cn.zhige.dao.impl.test<cn.zhige.dao.impl.ZhigeDao> //ParameterizedType 参数化类型
class cn.zhige.dao.impl.ZhigeDao//实际类型 //getAcutalTypeArguments() 返回的是实际类型数组
ZhigeDao //clazz.getSimpleName() 返回的是类的简单名称