I have two codes, in two different java projects, doing almost the same thing, (unmarshalling the input of a webservice according to an xsd-file).
But in one case I should write this: (Input is a placeholder name) ( element is OMElement input )
ClassLoader clInput = input.ObjectFactory.class.getClassLoader();
JAXBContext jc = JAXBContext.newInstance("input", clInput);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Input input = (Input)unmarshaller.unmarshal( element.getXMLStreamReader() );
and in the other lib I must use JAXBElement.getValue(), because it is a JAXBElement that is returned, and a simple (Input) cast simply crashes:
Input input = (Input)unmarshaller.unmarshal( element.getXMLStreamReader() ).getValue();
Do you know what leads to such a difference ?
It depends on the presence of XmlRootElement annotation on the class of your root element.
If you generate your JAXB classes from an XSD, the following rules are applied:
For that reason I often choose anonymous types for root elements.
You can customize the class name of this anonymous type with a customization file. E.g. create a bindings.xjc file like this:
You need to add to your JAXB generated class proper
@XMLRootElement
- it should have namespace:Have a look at the related question (there are a lot of good tips): Class Cast Exception when trying to unmarshall xml?
Modifying generated java classes, I don't agree. Not allowing all possible xsd format, I don't agree.
Thanx to all your explanations an links, this is the code I've have written so as to take care of both cases, using Annotation Introspection. It works for output as well as input, and is (in my taste) more generic:
I have the same problem. JAXB unmarshaller.unmarshal returns a
JAXBElement<MyObject>
instead of desiredMyObject
.I found and removed
@XmlElementDecl
. The problem is solved.If the root element uniquely corresponds to a Java class then an instance of that class will be returned, and if not a
JAXBElement
will be returned.If you want to ensure that you always get an instance of the domain object you can leverage the
JAXBInstrospector
. Below is an example.Demo
Output