我想使用反射获取泛型实例:
this.wrapperInstance = ((Class<WRAPPER>) ((ParameterizedType) (getClass().getGenericSuperclass())).getActualTypeArguments()[1]).newInstance();
但我例外:
java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
不知道问题出在哪里,也许有人可以帮助我吗?有完整的类代码:
public class XMLUtils<MODEL extends AbstractModel, WRAPPER extends WraperInterface<MODEL>> {
private WRAPPER wrapperInstance;
@SuppressWarnings("unchecked")
public XMLUtils() throws InstantiationException, IllegalAccessException {
this.wrapperInstance = ((Class<WRAPPER>) ((ParameterizedType) (getClass().getGenericSuperclass())).getActualTypeArguments()[1]).newInstance();
}
@SuppressWarnings("unchecked")
public List<MODEL> loadDataFromXML(String fileName) {
try {
File pajamuFile = new File(
UserDataLoader.INSTANCE.getCurrentUserFolder() + fileName);
JAXBContext context = JAXBContext.newInstance(wrapperInstance.getClass());
Unmarshaller um = context.createUnmarshaller();
WRAPPER wrapper = (WRAPPER) um.unmarshal(pajamuFile);
return wrapper.getDataList();
} catch (JAXBException e) {
e.printStackTrace();
return new ArrayList<MODEL>();
}
}
public void saveDataToXML(List<MODEL> dataList, String fileName) {
try {
File pajamuFile = new File(
UserDataLoader.INSTANCE.getCurrentUserFolder() + fileName);
JAXBContext context = JAXBContext.newInstance(wrapperInstance.getClass());
Marshaller m = context.createMarshaller();
WRAPPER wrapper = wrapperInstance;
wrapper.setDataList(dataList);
m.marshal(wrapper, pajamuFile);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
在谷歌我发现最类似的情况,但与春天,这里我不使用弹簧,所以也许有任何明确的解决方案,我想做的。
最佳答案
不知道哪里出了问题,也许有人可以帮我
该错误消息是不言自明的。以下语句返回Class
:
(getClass().getGenericSuperclass())
您正在尝试将其投射到
ParameterizedType
((ParameterizedType) (getClass().getGenericSuperclass()))
Class
和ParameterizedType
是兄弟姐妹。兄弟不是姐妹,因此试图将他们彼此融合会很残酷。话虽如此,对您的问题的快速解决方案是要求客户端代码将
Class
类型传递给您的XmlUtils
类。public class XMLUtils<MODEL extends AbstractModel, WRAPPER extends WraperInterface<MODEL>> {
private WRAPPER wrapperInstance;
public XMLUtils(Class<WRAPPER> wrapperInstance) throws InstantiationException, IllegalAccessException {
this.wrapperInstance = wrapperInstance
}
//more code follows
}