gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:17:24 24 4
gpt4 key购买 nike

如何使用反射查找传递给父类(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com