gpt4 book ai didi

java - 如何使用 Java Reflection 从 ParameterizedType 获取 GenericDeclaration 的类型?

转载 作者:行者123 更新时间:2023-12-01 20:21:25 26 4
gpt4 key购买 nike

我想分析类MyComponent中声明的字段变量,并且我想获取字段类的GenericDeclartion类型,而不是它在MyComponent中声明的类型。演示如下。

public class SomeConfig<OP extends Operation> {
private OP operation;

public SomeConfig(OP op) {
this.operation = op;
}
}

public class MyComponent {
private SomeConfig<?> config;

public MyComponent(SomeConfig<?> config) {
this.config = config;
}
}

public class MyAnalysis {
public static void main(String[] args) {
Class clazz = MyComponent.class;
Field[] fields = clazz.getDeclaredFields();
for (Field f : fields) {
Type type = f.getGenericType();
if(type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType)type;
System.out.println(pType.getActualTypeArguments()[0]); // which prints "?" for sure
}
}
}
}
<小时/>

问题:打印的结果是“?”一定。但我想要的只是获取要打印的 Operation 类型而不是“?”。可以实现吗?

最佳答案

But all I want is to get the type of Operation

泛型在编译后会被删除,因此您无法在运行时以这种方式访问​​它们。

为了满足您的需求,您可以更改 SomeConfig 构造函数以传递参数化类型的类实例:

public class SomeConfig<OP extends Operation> {
private OP operation;
private Class<OP> clazz;

public SomeConfig(OP op, Class<OP> clazz) {
this.operation = op;
this.clazz = clazz;
}
}

现在,clazz 字段可用于了解类型的类。

关于java - 如何使用 Java Reflection 从 ParameterizedType 获取 GenericDeclaration 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44615363/

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