簡體   English   中英

如何使用Java Reflection從ParameterizedType獲取GenericDeclaration的類型?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM