【发布时间】:2017-11-20 18:32:39
【问题描述】:
我想分析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 的类型而不是“?”。可以实现吗?
【问题讨论】:
标签: java generics reflection parameterized-types