使用反射在 Java 中获取泛型参数的类型 [英] Get type of a generic parameter in Java with reflection
本文介绍了使用反射在 Java 中获取泛型参数的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以获取泛型参数的类型?
Is it possible to get the type of a generic parameter?
示例:
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屋!
查看全文