我遇到javax.xml.bind.Binder implementation of EclipseLink Moxy的问题:当我从DOM文档实例解组我的对象时,我的绑定类中注释的unmarshal callback methods(在我的情况下是afterUnmarshal)从未被调用过。
问题似乎出现在Binder使用的org.eclipse.persistence.oxm.XMLUnmarshaller实例中:负责调用回调方法的unmarshalListener始终为null。此代码演示了此问题:
//Instantiate a JAXBContext
JAXBContext context = JAXBContext.newInstance(MyObject.class);
//Create a "standard" unmarshaller
JAXBUnmarshaller standardUnmarshaller = (JAXBUnmarshaller) context.createUnmarshaller();
//assertion is ok
assert standardUnmarshaller.getXMLUnmarshaller().getUnmarshalListener() != null;
//Create a Binder
XMLBinder xmlBinder = ((JAXBBinder) context.createBinder()).getXMLBinder();
//Use reflection tricks to get the unmarshaller (fest-reflect is used for conciseness)
XMLUnmarshaller binderUnmarshaller = Reflection.field("unmarshaller").ofType(XMLUnmarshaller.class).in(xmlBinder).get();
//assertion error here
assert binderUnmarshaller.getUnmarshalListener() != null;
这不容易修复,因为没有javax.xml.bind.Unmarshaller实例(在Binder上下文中不存在),org.eclipse.persistence.jaxb.JAXBUnmarshalListener无法实例化。 Moxy中没有其他XMLUnmarshalListener实现可用于替换JAXBUnmarshalListener。
我想出了这个解决方法,其中包括从“标准”JAXB unmarshaller重用JAXBUnmarshalListener实例。 :
//Instantiate a JAXBContext
JAXBContext context = JAXBContext.newInstance(MyObject.class);
//Create a Binder
JAXBBinder binder = (JAXBBinder) context.createBinder();
//Create an standard unmarshaller to reuse its unmarshalListener
JAXBUnmarshaller standardUnmarshaller = (JAXBUnmarshaller) context.createUnmarshaller();
//Use reflection for setting the binder's unmarshallerListener (fest-reflect again)
XMLUnmarshaller unmarshaller = Reflection.field("unmarshaller").ofType(XMLUnmarshaller.class).in(binder.getXMLBinder()).get();
unmarshaller.setUnmarshalListener(standardUnmarshaller.getXMLUnmarshaller().getUnmarshalListener());
//my unmarshal callbacks are called now
MyObject myObject = binder.unmarshal(domDocument);
我想问题与编组方法的问题是一样的,但我没有调查这种情况,因为我没有使用marshal回调。
我测试了javax.xml.bind.Binder的JAXB RI实现,并且正确调用了回调方法。虽然,我不能选择使用RI,因为它不会保留原始DOM文档中的注释节点。
我是否错过了Moxy配置中的某些内容,或者这是实施中的错误?如果有错误,是否有比我使用的更简单的解决方法?