LibraryLink ToToggle FramesPrintFeedback

Chapter 17. Using A JAXBContext Object

The JAXBContext object is a low-level object used by the runtime. It allows the runtime to convert between XML elements and their corresponding Java representations. An application developer generally does not need to work with JAXBContext objects. The marshaling and unmarshaling of XML data is typically handled by the transport and binding layers of a JAX-WS application.

However, there are instances when an application will need to manipulate the XML message content directly. In two of these instances:

You will need instantiate a JAXBContext object using one of the two available JAXBContext.newInstance() methods.

JAXBContext objects are resource intensive to instantiate. It is recommended that an application create as few instances as possible. One way to do this is to create a single JAXBContext object that can manage all of the JAXB objects used by your application and share it among as many parts of your application as possible.

[Tip]Tip

JAXBContext objects are thread safe.

The JAXBContext class provides a newInstance() method, shown in Example 17.1, that takes a list of classes that implement JAXB objects.


The returned JAXBObject object will be able to marshal and unmarshal data for the JAXB object implemented by the classes passed into the method. It will also be able to work with any classes that are statically referenced from any of the classes passed into the method.

While it is possible to pass the name of every JAXB class used by your application to the newInstance() method it is not efficient. A more efficient way to accomplish the same goal is to pass in the object factory, or object factories, generated for your application. The resulting JAXBContext object will be able to manage any JAXB classes the specified object factories can instantiate.

The JAXBContext class provides a newInstance() method, shown in Example 17.2, that takes a colon (:) seperated list of package names. The specified packages should contain JAXB objects derived from XML Schema.


The returned JAXBContext object will be able to marshal and unmarshal data for all of the JAXB objects implemented by the classes in the specified packages.