Java 如何使用模板解组?
我猜是错误的Java 如何使用模板解组?,java,jaxb,Java,Jaxb,我猜是错误的 T bobj = (T) jaxbUnmarshaller.unmarshal(file); 它总是返回null 使用非模板进行测试,它工作并返回一个Customer类,与模板一起使用时仅返回null 原始代码 XMLObj<Customer> XMLtool = new XMLObj<Customer>(Customer.class); Customer c = XMLtool.ConvertXMLToObject("c:\\file2.xml");
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;
}
}
xmlobjxmltool=newxmlobj(Customer.class);
客户c=XMLtool.ConvertXMLToObject(“c:\\file2.xml”);
公共类XMLObj{
最终类typeParameterClass;
公共XMLObj(类typeParameterClass){
this.typeParameterClass=typeParameterClass;
}
公共T ConvertXMLToObject(字符串路径)
{
//将XML转换为对象
试一试{
文件=新文件(路径);
if(file.exists())
{
JAXBContext JAXBContext;
jaxbContext=jaxbContext.newInstance(typeParameterClass.getClass());
解组器jaxbUnmarshaller=jaxbContext.createUnmarshaller();
T bobj=(T)jaxbUnmarshaller.unmarshal(文件);
系统输出打印LN(bobj);
返回bobj;
}
其他的
Logger.getInstance().process_消息(“ConvertObjectToXML中不存在文件”);
}捕获(JAXBEException e){
//TODO自动生成的捕捉块
Logger.getInstance().process_消息(例如getMessage());
}
返回null;
}
}
尝试更改此行:
jaxbContext = JAXBContext.newInstance(typeParameterClass.getClass());
为此:
jaxbContext = JAXBContext.newInstance(typeParameterClass);
typeParameterClass.getClass()
返回一个类的类型java.lang.class
,而typeParameterClass
本身有一个类的类型Customer
,这是您要解组的类