尼尔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