Marshalling sub-classes

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.

Advertisements
This entry was posted in Java, JAXB, xml. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s