Java中如何获取一个类中泛型的实际类型
1.学习之前我们先来了解一些泛型的术语<>: 念做typeofList
2.泛型反射相关APIType[] getGenericInterfaces():获得当前类实现的泛型接口(参数化类型)举例1:1)定义类A,C 接口B
//类Bpublic interface B{}//类Cpublic class C{}//A实现B,向B传入实际类型参数Cpublic class A implements B
2)测试代码
A a = new A();Type[] types = a.getClass().getGenericInterfaces();for (Type type : types) {
System.out.println(type);//结果是:B
Type[] getGenericSuperclass():获得带有泛型的父类举例2:1)定义3个类A,B,C
//类Bpublic class B{}//类Cpublic class C{}//A继承B,向B传入实际类型参数Cpublic class A extends B
2)测试代码
A a = new A();Type type = a.getClass().getGenericSuperclass();System.out.println(type);//结果是:B
ParameterizedType:参数化类型接口,Type的子接口通过上面两个案例可知getGenericInterfaces和getGenericSuperclass可以获取到参数化类型B
A a = new A();//获得带有泛型的父类Type type = a.getClass().getGenericSuperclass();System.out.println(type);//结果是:B
获取接口泛型的实际类型参数做法跟上面代码差不多,只需要把Type type = a.getClass().getGenericSuperclass(),改成Type type = a.getClass().getGenericInterfaces()就可以了。
讲解完毕,如有错漏请多多包含!!!!!