使用反射获取Java中泛型参数的类型是否可能获得泛型参数的类型?例如: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>());
}}
3 回答
侃侃尔雅
TA贡献1801条经验 获得超16个赞
Class<T> persistentClass = (Class<T>) ((ParameterizedType)getClass().getGenericSuperclass()) .getActualTypeArguments()[0];
富国沪深
TA贡献1790条经验 获得超9个赞
Method m;Type[] genericParameterTypes = m.getGenericParameterTypes();for (int i = 0; i < genericParameterTypes.length; i++) { if( genericParameterTypes[i] instanceof ParameterizedType ) { Type[] parameters = ((ParameterizedType)genericParameterTypes[i]).getActualTypeArguments();//parameters[0] contains java.lang.String for method like "method(List<String> value)" } }
添加回答
举报
0/150
提交
取消