[英]How to get the Type of GenericDeclaration from ParameterizedType using Java Reflection?
I want to analysis the declared field variable in class MyComponent
, and I want to get the GenericDeclartion's type of the field class, not the type it's declared in MyComponent
. 我想分析
MyComponent
类中声明的字段变量,并且想要获得GenericDeclartion字段类的类型,而不是它在MyComponent
声明的类型。 The demo is below. 该演示如下。
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
}
}
}
}
The Problem: The printed result is "?" 问题:打印结果是“?” for sure.
当然。 But all I want is to get the type of
Operation
to be printed instead of "?". 但是,我要获取的是要打印的
Operation
类型,而不是“?”。 Is it achievable? 可以实现吗?
But all I want is to get the type of Operation
但是我想要的就是获取操作类型
Generics are erased after compilation, so you could not access to them in this way at runtime. 泛型在编译后会被擦除,因此您无法在运行时以这种方式访问它们。
To achieve your need, you could change the SomeConfig
constructor in order to pass the class instance of the parameterized type : 为了满足您的需求,您可以更改
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;
}
}
Now the clazz
field may be used to know the class of the type. 现在,
clazz
字段可用于了解类型的类别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.