I'm trying to specify a implementation class for an XSD-Type. Here's a minimal example schema:
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="rd.test"
xmlns:tns="rd.test" elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="2.0">
<complexType name="DocumentType">
<annotation>
<appinfo>
<jaxb:class implClass="rd.DocumentEx" />
</appinfo>
</annotation>
<sequence>
<element name="element" type="tns:DocumentType" />
</sequence>
<attribute name="title" type="string" />
</complexType>
<element name="document" type="tns:DocumentType"/>
</schema>
I'm using the standard xjc-tool from the Java JDK (1.7) for now (but I've also tested with maven-jaxb2-plugin, with the same results).
For a short test I used the following XML-document:
<?xml version='1.0' standalone='yes' ?>
<document title="testDocument">
<element title="testElement" />
</document>
When I run the following test program, the results differ for the top-level document element (testDocument) and the contained child element (testElement). The root is of type "DocumentType", i.e. ignoring the specified implClass-directive, whereas the element is of type "DocumentEx", which is the expected result. In the generated ObjectFactory the appropriate instantiation seems correct, but it seems to be not used for the rootElement:
public DocumentType createDocumentType() {
return new DocumentEx();
}
Here is the test program:
InputStream inp=new FileInputStream(new File("test.xml"));
JAXBContext jaxbContext = JAXBContext.newInstance("test.rd");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
JAXBElement el = (JAXBElement)unmarshaller.unmarshal(inp);
Object obj = el.getValue();
System.out.println("doc: " + obj);
// result: "doc: test.rd.DocumentType@d1c5bb0"
DocumentType doc = (DocumentType)obj;
Object obj2=doc.getElement();
System.out.println("obj2: " + obj2);
// result: "obj2: rd.DocumentEx@d1c5bb0"
I get the same result, if I specify the implClass for the element instead of for the complexType.
Why is the implClass ignored for the root-element? Any ideas and hints are appreciated!
Extension to clarify my intention:
I don't want to reference an existing, jaxb-annotated class, but use the auto-generated DocumentType-Class as base class for extionsion with additional attributes and methods. For a later direct marshalling back to XML, I have to keep the relation to the XSD-Type. Therefore the implClass-directive actually is the appropriate (as far as I know) way to instrument the jaxb-generation of the type-classes.
And it's working perfectly for the inner elements (the 'element' with title 'testElement' inside the document-tag)!! Unfortunately the unmarshaller does NOT use the implClass-specified class for instantiating the root-element correctly. See the result-comments in the program excerpt above (doc vs. obj2).