欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

(转)java反射获得泛型参数GETGENERICSUPERCLASS()

程序员文章站 2022-03-21 19:42:25
public class Person { 2 3 } 4 5 import java.lang.reflect.ParameterizedType; 6 import java.lang.reflect.Type; 7 8 public class Student extends Person {... ......
 public class Person<T> {
 2 
 3 }
 4 
 5 import java.lang.reflect.ParameterizedType;
 6 import java.lang.reflect.Type;
 7 
 8 public class Student extends Person<Student> {
 9 public static void main(String[] args) {
10 Student st=new Student();
11 Class clazz=st.getClass();
12 //getSuperclass()获得该类的父类
13 System.out.println(clazz.getSuperclass());
14 //getGenericSuperclass()获得带有泛型的父类
15 //Type是 Java 编程语言中所有类型的公共高级接口。它们包括原始类型、参数化类型、数组类型、类型变量和基本类型。
16 Type type=clazz.getGenericSuperclass();
17 System.out.println(type);
18 //ParameterizedType参数化类型,即泛型
19 ParameterizedType p=(ParameterizedType)type;
20 //getActualTypeArguments获取参数化类型的数组,泛型可能有多个
21 Class c=(Class) p.getActualTypeArguments()[0];
22 System.out.println(c);
23 }
24 }
25 
26 打印结果:
27 
28 class com.test.Person
29 com.test.Person<com.test.Student>
30 class com.test.Student