我想错误在
T bobj = (T) jaxbUnmarshaller.unmarshal(file);
它总是返回null
使用非模板测试,它工作并返回一个Customer类,仅在与模板一起使用时返回null
原始代码
XMLObj<Customer> XMLtool = new XMLObj<Customer>(Customer.class);
Customer c = XMLtool.ConvertXMLToObject("c:\\file2.xml");
public class XMLObj<T> {
final Class<T> typeParameterClass;
public XMLObj(Class<T> typeParameterClass) {
this.typeParameterClass = typeParameterClass;
}
public T ConvertXMLToObject(String path)
{
//Convert XML to Object
try {
File file = new File(path);
if(file.exists())
{
JAXBContext jaxbContext;
jaxbContext = JAXBContext.newInstance(typeParameterClass.getClass());
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
T bobj = (T) jaxbUnmarshaller.unmarshal(file);
System.out.println(bobj);
return bobj;
}
else
Logger.getInstance().process_message("File not exist in ConvertObjectToXML");
} catch (JAXBException e) {
// TODO Auto-generated catch block
Logger.getInstance().process_message(e.getMessage());
}
return null;
}
}
答案 0 :(得分:0)
尝试更改此行:
jaxbContext = JAXBContext.newInstance(typeParameterClass.getClass());
对此:
jaxbContext = JAXBContext.newInstance(typeParameterClass);
typeParameterClass.getClass()
会返回java.lang.Class
类的类型,而typeParameterClass
本身的类型为Customer
,这是您要解组的类。