假设有两个类:Dao 和 PersonDao,它们的代码如下:
Dao:
public class Dao<T> { private Class<T> clazz; T getId(Integer id){ return null; } void save(T entity){ } }
PersonDao:
public class PersonDao extends Dao<Person> {
}
Person:
public class Person { private String name; private String street; public void setName(String name) { this.name = name; } public void setStreet(String street) { this.street = street; } public String getName() { return name; } public String getStreet() { return street; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", street='" + street + '\'' + '}'; } }
ReflectionUtil:
/** * 通过反射获得定义Class时声明的父类的泛型参数的类型 * 例如:public EmployeeDao extends BaseDao<Employee,String> * @param clazz: 子类对应的Class对象 * @param index: 泛型参数列表对应的位置,从0开始 */ public class ReflectionUtil { public static Class getSuperClassGenericType(Class clazz,int index){ // Type type= clazz.getGenericSuperclass(); // if(type instanceof ParameterizedType){ // ParameterizedType parameterizedType = (ParameterizedType) type; // Type[] args = parameterizedType.getActualTypeArguments(); // if(args !=null && args.length>0){ // Type arg = args[0]; // if(arg instanceof Class){ // return (Class)arg; // } // } // // } // return null;
//getSuperclass()获得该类的父类
//getGenericSuperclass()获得带有泛型的父类
//Type是 Java 编程语言中所有类型的公共高级接口。它们包括原始类型、参数化类型、数组类型、类型变量和基本类型。
Type genType= clazz.getGenericSuperclass();//获取带泛型参数的父类 if(!(genType instanceof ParameterizedType)){ return Object.class; } Type[] param = ((ParameterizedType) genType).getActualTypeArguments();//获取真实泛型参数 if(index >= param.length || index < 0){ return Object.class; } if(!(param[index] instanceof Class)){ return Object.class; } return (Class) param[index]; } @Test public void getSuperClassGenericTypeTest(){ PersonDao personDao = new PersonDao(); Class clazz = ReflectionUtil.getSuperClassGenericType(personDao.getClass(),0); System.out.println(clazz); } }
通过ReflectionUtil中的静态方法getSuperClassGenericType()获取父类中泛型参数对应的Class对象后,调用newInstance可以创建对应的实例,Dao中的getId方法就可以返回泛型参数对应的实例。
浙公网安备 33010602011771号