先看以下代码:
定义一个带泛型的父类
package go.jacob.day518;
public class Person <T>{
}
让Student继承Person类
public class Student extends Person<Student> {
}
测试类
public class App {
public static void main(String[] args) {
Student stu = new Student();
Class clazz = stu.getClass();
System.out.println("Student类:" + clazz);
System.out.println("Student父类:" + clazz.getSuperclass());
// getGenericSuperclass()获得带有泛型的父类
// Type是 Java 编程语言中所有类型的公共高级接口。它们包括原始类型、参数化类型、数组类型、类型变量和基本类型。
System.out.println("Student的Generic父类:" + clazz.getGenericSuperclass());
Type type=clazz.getGenericSuperclass();
//ParameterizedType参数化类型,即泛型
ParameterizedType p=(ParameterizedType)type;
Class c=(Class)p.getActualTypeArguments()[0];
System.out.println(c);
}
}
运行结果:
Student类:class go.jacob.day518.Student
Student父类:class go.jacob.day518.Person
Student的Generic父类:go.jacob.day518.Person<go.jacob.day518.Student>
class go.jacob.day518.Student
简单来说,clazz.getGenericSuperclass()可以获得带泛型的父类,这种类型在java中叫做Type
然后用ParameterizedType p=(ParameterizedType)type; 与Class c=(Class)p.getActualTypeArguments()[0];获得泛型的具体类型