[英]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
和來自它的對象( Method
, Field
),可以得到這些。 但是,您無法從任何舊的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.