一、getGenericSuperclass()和getActualTypeArguments()基本使用方法:
import java.lang.reflect.ParameterizedType;
public class TT extendsTT2<Integer> {
public static void main(String[] args) {
System.out.println(((ParameterizedType) newTT().getClass()
.getGenericSuperclass()).getActualTypeArguments()[0]);
}
}
//output:classjava.lang.Integer
说明: getGenericSuperclass() 通过反射获取当前类表示的实体(类,接口,基本类型或void)的直接父类的Type。getActualTypeArguments()返回參数数组。
二、泛型
DAO 模拟
BaseDaoImpl类:
packagecom.mrlun.oa.test;
importjava.lang.reflect.ParameterizedType;
@SuppressWarnings("unchecked")
public classBaseDaoImpl<T> {
private Classclazz;
publicBaseDaoImpl() {
ParameterizedTypept = (ParameterizedType) this.getClass()
.getGenericSuperclass();
this.clazz =(Class) pt.getActualTypeArguments()[0];
System.out.println("Type为: " + clazz.getSimpleName());
}
public void save() {
System.out.println("Type为: " + clazz.getSimpleName());
}
}
UserDao类:
package com.mrlun.oa.test;
public class UserDao extendsBaseDaoImpl<Users>{
}
測试类:
package com.mrlun.oa.test;
public class Test{
public static void main(String[] args) {
UserDao userdao=new UserDao();
userdao.save();
}
}
//output:
Type为: Users(new子类时会调用父类的默认的构造方法)
Type为: Users
这时,我们就能够使用泛型来简化DAO的操作,省去了写N多有反复的方法的DAO的时间。