Why can’t JAXB find my jaxb.index when running inside Apache Felix?

OK, this took quite some digging, but the answer is not that surprising and not even that complicated:

JAXB can’t find jaxb.index, because by default, newInstance(String) uses the current thread’s class loader (as returned by Thread.getContextClassLoader()). This doesn’t work inside Felix, because the OSGi bundles and the framework’s threads have separate class loaders.

The solution is to get a suitable class loader from somewhere and use newInstance(String, ClassLoader). I got a suitable class loader from one of the classes in the package that contains jaxb.index, a sensible choice for flexibility reasons probably is ObjectFactory:

ClassLoader cl = my.package.name.ObjectFactory.class.getClassLoader();
JAXBContext jc = JAXBContext.newInstance("my.package.name", cl);

Maybe you could also get at the class loader that the Bundle instance is using, but I couldn’t figure out how, and the above solution seems safe to me.

Leave a Comment