java - 使用反射访问类型参数

标签 java reflection

如何使用反射查找传递给父类(super class)的类型参数值?

例如,给定 Bar.class,我如何发现它传递 Integer.classFoo 的类型参数 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/

相关文章:

reflection - 在 golang 中将 interface{} 转换为 *[]int

java - Android 风格和主题

java - Spring Boot 应用程序中的 JVM "EXCEPTION_ACCESS_VIOLATION"崩溃

Java:如何在覆盖方法(祖 parent 方法)中调用 super().super()

Java 合成 XML : Button Style properties won't work

java - ReflectionTestUtils 设置字段, Spring 值注释返回 NPE

java - 将多个项目(maven2)导入到eclipse中

java - 使用 .getClass() 时如何将参数传递给构造函数?

c# - 有没有办法在运行时获取属性的声明方法/属性

.net - 是否有框架属性可以在.Net 中隐藏成员以防止反射?