I am trying to create a sample test application which converts an object to JaxbRepresentation. But when I try to run this, it gives me an error.
Main.java file
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 created an empty jaxb.index file at the location where it was looking for the object factory class. That fixed my problem.
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
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
In my case I was able to solve the problem by changing the instantiation of the JAXBContext. It can either be instantiated with the package name or the ObjectFactory class as a parameter.
When instantiating with the package name:
com.myexample.test.ObjectFactory objectFactory = new com.myexample.test.ObjectFactory();
JAXBContext jaxbContext = JAXBContext.newInstance(objectFactoryMessageBody.getClass().getPackage().getName());
It gave the error:
"com.myexample.test" doesnt contain ObjectFactory.class or jaxb.index
No errors when instantiating with the class name:
com.myexample.test.ObjectFactory objectFactory = new com.myexample.test.ObjectFactory();
JAXBContext jaxbContext = JAXBContext.newInstance(objectFactoryMessageBody.getClass());
If you have an instantiation of your object factory like
private ObjectFactory of;
..then the safest, most reliable way to get a Context to Marshall with is:
JAXBElement<GreetingListType> gl = of.createGreetings( grList );
JAXBContext jc = JAXBContext.newInstance(of.getClass());
Marshaller m = jc.createMarshaller();