我有一個javax.xml.bind.Binder implementation of EclipseLink Moxy:我的綁定類中註釋的unmarshal callback methods(在我的情況下是Unmarshal)問題在我從DOM文檔實例解組我的對象時從未被調用過。JAXB unmarshal回調沒有用Binder實現的EclipseLink調用Moxy
問題似乎在Binder所使用的org.eclipse.persistence.oxm.XMLUnmarshaller實例中:負責調用回調方法的unmarshalListener始終爲空。此代碼演示了此問題:
//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;
這不容易固定,因爲org.eclipse.persistence.jaxb.JAXBUnmarshalListener離不開javax.xml.bind.Unmarshaller實例,它不會在粘合劑方面存在被實例化。在Moxy中沒有可用的其他XMLUnmarshalListener實現來替換JAXBUnmarshalListener。
我想出了這個解決方法,它包括重用JAXBUnmarshaller中的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);
我想這個問題是與編組方法是相同的,但我沒有調查這種情況下,我不使用元帥回調。
我測試了javax.xml.bind.Binder的JAXB RI實現,並且正確調用了回調方法。雖然,但我不能選擇使用RI,因爲它不保留原始DOM文檔中的註釋節點。
我錯過了Moxy配置中的一些東西,或者這是實施中的錯誤嗎?如果有錯誤,是否有比我使用的更簡單的解決方法?