如何使用反射查找传递给父类(super class)的类型参数值?
例如,给定 Bar.class
,我如何发现它传递 Integer.class
给 Foo
的类型参数 T
?
public class Foo<T> {
}
public class Bar extends Foo<Integer> {
}
谢谢!
最佳答案
你可以试试
ParameterizedType type = (ParameterizedType) Bar.class.getGenericSuperclass();
System.out.println(type.getRawType()); // prints; class Foo
Type[] actualTypeArguments = type.getActualTypeArguments();
System.out.println(actualTypeArguments[0]); // prints; class java.lang.Integer
这只适用于 Bar 是一个扩展特定 Foo 的类。如果您像下面这样声明一个变量,您将无法在运行时确定 intFoo 的参数类型。
Foo<Integer> intFoo = new Foo<Integer>();
关于java - 使用反射访问类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4565519/