[英]Class cannot be cast to ParameterizedType
public class FrontUtil<T> {
public List<Map<String, String>> tableGen(List<Map<String, String>> theads, List<T> tbodys){
List<Map<String, String>> frontList = null;
for (T t : tbodys) {
*Class<T> clazz =(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];*
for (Map<String, String> title : theads) {
try {
Field field = clazz.getDeclaredField(title.get("columnClass"));
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();
String content = getMethod.invoke(t).toString();
Map<String, String> temp = new HashMap<String, String>(0);
temp.put(title.get("columnName"), content);
frontList.add(temp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return frontList;
}
}
the stack: 堆栈:
java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
*****FrontUtil.tableGen(FrontUtil.java:19)
*****action.MaterialFactoryAction.list(MaterialFactoryAction.java:78)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
I would like to get the Actual class of T though 我想获得T的实际班级
Class<T> clazz =(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
but it can't work . 但这没用。 Any suggestion would be appreciated,thanks.
任何建议,将不胜感激,谢谢。
The answer is: you can't. 答案是:您不能。 Because of type erasure that information no longer exists at run time.
由于类型删除 ,信息在运行时不再存在。
Pass in a Class
argument when you create your FrontUtil
instance. 创建
FrontUtil
实例时传递Class
参数。
private Class<T> clazz;
public FrontUtil(Class<T> clazz) {
this.clazz = clazz;
}
Then use that Class
object wherever you need it. 然后在需要的地方使用该
Class
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.