package top.demo.dao;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class TTest {
public static void main(String argv[]) {
//得到带父类泛型信息的Type对象 注意:Class 实现了 Type Type为接口
Type type=B.class.getGenericSuperclass();
//ParameterizedType接口 继承了 Type接口 所以可以互转
if(type instanceof ParameterizedType)
{
ParameterizedType parameterizedType=(ParameterizedType)type;
//可以说 Type携带了父类的泛型信息 又由于ParameterizedType 继承type接口 可以得到泛型信息
//调用方法 得到真实参数 (也就是泛型的真实类型) 为什么是数组 因为泛型可能不止一个
Type[] types=parameterizedType.getActualTypeArguments();
//得到泛型的真实类型后需要 等到类型名字 那么就转换为Class拿到名字
for(Type ty:types)
{
Class cl=(Class)ty;
System.out.println(cl.getName());
}
}
}
}
class A<K,V>{
public A(){
}
public K testK;
public V testV;
}
class B extends A<String,Integer>{
public B(){
}
}
通过反射得到父类泛型的类型
最新推荐文章于 2024-07-16 02:08:53 发布