用反射获取Java中的泛型参数的类型 [英] Get type of a generic parameter in Java with reflection
本文介绍了用反射获取Java中的泛型参数的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能获得泛型参数的类型?
一个例子:
pre > public final class Voodoo {
public static void chill(List<?> aListWithTypeSpiderMan){
//这里我想获得类对象'SpiderMan'
Class typeOfTheList = ???;
public static void main(String ... args){
chill(new ArrayList< SpiderMan>());
}
}
解决方案
One我有一次偶然发现,它看起来像
Class< T> persistentClass =(Class< T>)
((ParameterizedType)getClass()。getGenericSuperclass())
.getActualTypeArguments()[0];
所以似乎有一些反思 - 魔法让我感到很遗憾并不完全明白......对不起。
Is it possible to get the type of a generic parameter?
An example:
public final class Voodoo {
public static void chill(List<?> aListWithTypeSpiderMan) {
// Here I'd like to get the Class-Object 'SpiderMan'
Class typeOfTheList = ???;
}
public static void main(String... args) {
chill(new ArrayList<SpiderMan>());
}
}
解决方案
One construct, I once stumbled upon looked like
Class<T> persistentClass = (Class<T>)
((ParameterizedType)getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
So there seems to be some reflection-magic around that I unfortunetly don't fully understand... Sorry.
这篇关于用反射获取Java中的泛型参数的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文