尼爾Gafter介紹type tokens(例如Class<String>
)。假設在運行時可以訪問Class<String>
的實例,是否可以在運行時檢索通用類型(String
)?是否可以在運行時檢索用於類型令牌的通用類型(即類別<T>)?
我在尋找類似於Method.getGenericReturnType()的東西。
尼爾Gafter介紹type tokens(例如Class<String>
)。假設在運行時可以訪問Class<String>
的實例,是否可以在運行時檢索通用類型(String
)?是否可以在運行時檢索用於類型令牌的通用類型(即類別<T>)?
我在尋找類似於Method.getGenericReturnType()的東西。
有可能使用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
我認爲它只適用於字段/方法。由於類型擦除,我們無法在運行時獲得類特定的泛型類型。如果你有上課的機會,你似乎可以進行破解。閱讀discussion。
這聽起來像你想要的是ParameterizedType
。
您通過反思Class
和來自它的物體(Method
,Field
)得到這些結果。但是,您無法從任何舊的Class
對象獲取ParameterizedType
;您可以從代表擴展泛型類或接口的類型的Class
實例中獲得一個實例。
好的,但那麼,如何專門進行? – JVerstry 2012-07-30 21:37:07
不知道你的意思。如果你已經有了Class實例,你還想要什麼? – jtahlborn 2012-07-30 18:19:34
用作通用參數的類型。 – JVerstry 2012-07-30 18:28:51
_what_?一個類實例或某個類型的名字?也許你可以添加一些僞代碼,說明你正在尋找什麼...... – jtahlborn 2012-07-30 18:41:25