Friday, February 24, 2012

JAXB - II (jaxb.index file and ObjectFactory)

I was getting a Exception like, javax.xml.bind.JAXBException: "doesnt contain ObjectFactory.class or jaxb.index" while trying to create a JAXBContext using JAXBContext.newInstance(String contextPath).

It took me a while to figure out what went wrong. So now that I've got things working correctly, I thought I'd post this example and solution to hopefully save you some time.

When we create a marshaller, we first need to create a JAXBContext via its newInstance() factory method. You can create a context for a specific JAXB class  or you can create a context for a list of packages.

There are two ways to resolve this issue : 
  - By creating ObjectFactory
  - By adding jaxb.index file

jaxb.index :

The jaxb.index file is a text file contains a listing of the classes on the containing package that have JAXB annotations.
Note : The name of the clases is their simple name not their classified name.
 

Rather than creating a ObjectFactory, I guess adding a jaxb.index file is much easy part. Just you need to add class names to the file and place the file in the package (directory) where your JAXB annotated classes reside.
Its just the class name, not the fully qualified name (the package name is determined by the directory you placed the file in) or the.class name.

     JAXBContext context = JAXBContext.newInstance(className.getClass().getPackage().getName());

If the package following package does not have jaxb.index file, this change will cause the test to throw the JAXBException. Add the file and everything works great.

No comments:

Post a Comment

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...