簡體   English   中英

是否有可能檢索用於類型標記的通用類型(即Class <T> )在運行時?

[英]Is it possible to retrieve the generic type used for a type token (i.e. Class<T>) at runtime?

Neal Gafter引入了類型標記 (例如Class<String> )。 假設在運行時可以訪問Class<String>的實例,是否可以在運行時檢索泛型類型( String )?

我正在尋找類似於Method.getGenericReturnType()的東西。

我認為這僅適用於字段/方法。 由於類型擦除,我們在運行時無法獲得類特定的泛型類型。 如果您有權上課,似乎可以采取一些措施。 閱讀此討論

與C#不同,泛型在Java運行時不存在。 因此,您不能嘗試創建通用類型的實例或嘗試在運行時查找通用類型的類型。

聽起來您想要的是ParameterizedType

通過思考一個Class和來自它的對象( MethodField ),可以得到這些。 但是,您無法從任何舊的Class對象獲取ParameterizedType 您可以從Class實例獲得一個實例,該實例表示擴展通用類或接口的類型。

可以使用鮑勃·李(Bob Lee)對Gafter的小工具模式進行的改進:

public class GenericTypeReference<T> {

    private final Type type;

    protected GenericTypeReference() {
        Type superclass = getClass().getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
    }

    public Type getType() {
        return this.type;
    }   

    public static void main(String[] args) {

        // This is necessary to create a Class<String> instance
        GenericTypeReference<Class<String>> tr =
            new GenericTypeReference<Class<String>>() {};

        // Retrieving the Class<String> instance
        Type c = tr.getType();

        System.out.println(c);
        System.out.println(getGenericType(c));

    }

    public static Type getGenericType(Type c) {
        return ((ParameterizedType) c).getActualTypeArguments()[0];
    }

}

上面的代碼打印:

java.lang.Class<java.lang.String>
class java.lang.String 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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