tags:

views:

312

answers:

2

Do you always need an ObjectFactory class when using JAXB?

Without it I get this exception:

javax.xml.bind.JAXBException: "com.a.b.c" doesnt contain ObjectFactory.class or jaxb.index

I gather the ObjectFactory can be overkill. But given this exception I'm guessing you need it.. but not sure why?

+1  A: 

You get that exception when you use the JAXBContext.newInstance(String) factory method, where you pass in the package name as the argument. This does require the ObjectFactory to be there, otherwise, JAXB doesn't know which classes to process.

If you don't have an ObjectFactory, you need to JAXBContext.newInstance(Class...) instead, passing in the explicit list of annotated classes to add to the context.

skaffman
We always have the same root element. From the root we have a big hierarchy of classes/xml elements. So can we just do `JAXBContext.newInstance(OurRoot.class)`? Or do we need to pass in a list of *all* our classes?
Marcus
@Marcus: Generally you need only pass in the root class, yes, unless you have polymorphic associations in your annotations, in which case you need to pass those in as well. The methods generated in `ObjectFactory` can seem a little strange, and in most cases, you don't need to use them at all, you can just instantiate directly. They're most useful for creating `JAXBElement` wrappers.
skaffman
A: 

Instead of the ObjectFactory you can include a jaxb.index file which is a text file that contains a new line seperated list of Java classes.

For an example of using a jaxb.index file see:

Blaise Doughan