Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

It’s not uncommon to use superclasses to contain code that is used in multiple sub-classes. This prevents code duplication and allows the code to be maintained in one place instead of several. The normal way that you marshall JAXB classes will have your duplicating the marshaller. It is possible to use the superclass and only specify it once. If you have class Animal and it is extended by Cat and Dog. How would you marshall them without having to duplicate code?

JAXBContext jaxbContext = JAXBContext.newInstance(Animal.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter stringWriter = new StringWriter();
marshaller.marshal(watchForm, stringWriter);

You specify the parent class when you get the JAXB context instance. This will get you an error message saying that the particular instance (Dog or Cat) that you are trying to marshall isn’t known to this context. This is worked around by adding @XmlSeeAlso({Cat.class, Dog.class}) to Animal. This tells the JAXB context to also load their definitions.

August 21st, 2012

Posted In: Java, JAXB, xml

Leave a Reply

Your email address will not be published. Required fields are marked *

WP to LinkedIn Auto Publish Powered By : XYZScripts.com