JaxbRepresentation gives error "doesnt contain ObjectFactory.class or jaxb.index"

In my case I was able to resolve this by adding a file called "jaxb.index" in the same package folder as the JAXB annotated class. In that file list the simple, non-qualified names of the annotated classes.

For example, my file /MyProject/src/main/java/com/example/services/types/jaxb.index is simply one line (since I have only one JAXB typed class):

ServerDiagContent

which refers to the class com.example.services.types.ServerDiagContent


I got this error because of a ClassLoader issue, and I was able to solve it by explicitly passing the ClassLoader that JAXB should use, so this:

JAXBContext.newInstance(com.myexample.test.ObjectFactory.class.getPackage().getName());

gave an error, but worked properly when using:

JAXBContext.newInstance(com.myexample.test.ObjectFactory.class.getPackage().getName(),
                        com.myexample.test.ObjectFactory.class.getClassLoader());

which is probably similar to user3243752's answer, I bet that JAXB is automatically choosing the ClassLoader from the passed in class when using the #newInstance(Class... classesToBeBound) method signature.


I was using Spring and I just had to change

Jaxb2Marshaller mlr = new Jaxb2Marshaller();
mlr.setContextPaths("","");

to

Jaxb2Marshaller mlr = new Jaxb2Marshaller();
mlr.setPackagesToScan("","");

Ref1 & Ref2


To get rid of additional jaxb.index files you may use Java class to instantiate the context:

http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/JAXBContext.html#newInstance(java.lang.Class...)

Usually you need to pass in only single java class because other classes are "statically reachable from these class(es)" so JAXB is able to identify them.