I wrote in a previous article how easy it is to translate Java object to/from XML, without adding exotic library dependencies to your project; recently I’ve going through the code of one of my colleague and I discovered that the 3 line necessary to marshal and un-marshal the XML can be shortened to a single line using the JAXB utility class:

JAXBContext context = JAXBContext.newInstance(ObjectToConvert.class);
Unmarshaller u = context.createUnmarshaller();
return (ObjectToConvert) u.unmarshal(xmlInputStream);

// becomes
return (ClassToConvert)JAXB.unmarshal(xmlInputStream, ObjectToConvert.class);

// and 
JAXBContext context = JAXBContext.newInstance(objectInstanceToConvert.getClass());
Marshaller m = jc.createMarshaller();
m.marshal(objectInstanceToConvert, xmlOutputStream);

// becomes
JAXB.marshall(objectInstanceToConvert, xmlOutputStream)

Nice: one line of code to convert Java objects from/to XML. I didn’t notice this utility method in the JAXB library at first, so I was implementing those two methods in my code, more or less the same way. It’s always good to remove code.

4 Responses to “JAXB Tip: one line of code to marshall and unmarshall xml.”  

  1. 1 Blaise Doughan

    Hi Luigi,

    One thing to be aware of is that while using the JAXB class requires less lines of code, it does not provide the best performance. Normally the metadata processing is done at context creation time, then since the JAXBContext is thread safe it can be reused. When you use the JAXB class, the metadata initialization hit is taken for each marshal and unmarshal opertation.


  2. 2 Tim

    In addition, in at least some implementations of JAXB, each call to create a JAXBContext object will result in the creation of an anonymous class that does not get garbage collected. So over time, you’ll run out of memory (PermGen, presumably, though I haven’t tried to reproduce the problem directly in order to confirm that). If you’re just running the occasional unmarshal operation, you won’t care about either of these things, but if you’re doing lots of unmarshal operations, then reusing a single JAXBContext will make a big difference in both respects.


  3. 3 Luigi

    Awesome comment Tim, thanks for sharing.

  1. 1 JAXB Usage for single line conversion « Awe struck

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *


May 2011
« Feb   Jun »

Follow me

twitter flickr LinkedIn feed

Subscribe by email

Enter your email address:



Tag Cloud