经过反射获取父类泛型的类型
通过反射获取父类泛型的类型
如有以下类:
父类:
public class Person<T> { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
子类:
public class Student extends Person<Student> { private String num; public String getNum() { return num; } public void setNum(String num) { this.num = num; }; }
通过反射获取父类泛型的类型方法:
Class <T> entityClass = (Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
详细获取方式:
@Test @SuppressWarnings("rawtypes") public void testGetSuper(){ Student student = new Student(); Class clazz = student.getClass(); //获取该类的父类 System.out.println("该类的父类:"+clazz.getSuperclass()); //获得带有泛型的父类 Type type = clazz.getGenericSuperclass(); System.out.println("带泛型的父类:"+type); // 获取参数化类型(即泛型) ParameterizedType p = (ParameterizedType) type; //泛型可能是多个,获取自己需要的 Class clazz2 = (Class) p.getActualTypeArguments()[0]; System.out.println("父类泛型的类型:"+clazz2); }
输出结果为:
该类的父类:class com.test.bean.Person
带泛型的父类:com.test.bean.Person<com.test.bean.Student>
父类泛型的类型:class com.test.bean.Student