Wednesday, October 01, 2008

Using JAXB Without Annotations

The latest JAXB included with JDK 1.6 is really a great addition to the JDK making it easy to send objects around in XML format without requiring any third party libraries. All you have to do is put an @XmlRootElement annotation on a class and then call:

marshaller.marshal(Object, OutputStream);

Example class using @XmlRootElement:

@XmlRootElement
class MyClass {
  String name;
  String content;
}


To read the object back in, you simply call:



MyClass object = unmarshaller.unmarshal(InputStream);



But what if you are building a library that doesn’t know what the class is and doesn’t have the @XmlRootElement annotation?  Well it turns out that it’s almost just as easy without it you just need to let JAXB know what class you expect.



First get the JAXBContext like this:



JAXBContext context = JAXBContext.newInstance(object.getClass());


To marshal:



marshaller.marshal(new JAXBElement(new QName(object.getClass().getSimpleName()), object.getClass(), object), out);


To unmarshal:



JAXBElement o = unmarshaller.unmarshal(new StreamSource(inputStream), expectedType);
MyClass object = o.getValue();


That’s it.