[英]How to get the Type of GenericDeclaration from ParameterizedType using Java Reflection?
我想分析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
類型,而不是“?”。 可以實現嗎?
但是我想要的就是獲取操作類型
泛型在編譯后會被擦除,因此您無法在運行時以這種方式訪問它們。
為了滿足您的需求,您可以更改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
字段可用於了解類型的類別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.