文章内容
一、背景
有如下场景:
1、父类
1 2 3 4 | public abstract class Parent<T> { public Parent(){ } } |
2、子类
1 2 3 4 | public class Son<String> extends Parent<T> { public Son(){ } } |
- 通过子类获取子类的泛型名称
- 通过子类,获取子类的父类(超类)的泛型名称。
二、获取泛型类类名的方法
1、获取子类的泛型名称
1 2 | Son<String> son = new Son<>(); System.out.println(son.getClass().getTypeParameters()[ 0 ].getTypeName()); |
输出结果:String
2、获取子类的父类的泛型名称
获取子类的父类的泛型名称,就比上述的操作步骤中多了一个步骤,就是在1的方法上获取父类的class,然后再获取泛型名称,代码如下:
1 2 | Son<String> son = new Son<>(); System.out.println(son.getClass().getSuperclass().getTypeParameters()[ 0 ].getTypeName()); |
输出结果:T
3、获取抽象类泛型参数类名
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 | import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; public abstract class Test<T> { public Test() { super (); Type type = getClass().getGenericSuperclass(); Type[] params = ((ParameterizedType) type).getActualTypeArguments(); System.out.println(params[ 0 ]); } public static void main(String[] args) { Test<String> test = new Test<String>() { }; } } |
输出结果:
1 | class java.lang.String |