它就在那里,在它应该被索引的包中。不过,当我打电话时
JAXBContext jc = JAXBContext.newInstance("my.package.name");
我收到一个 JAXBException 说明
"my.package.name" doesnt contain ObjectFactory.class or jaxb.index
虽然它确实包含两者。
什么有效,但不是我想要的,是
JAXBContext jc = JAXBContext.newInstance(my.package.name.SomeClass.class);
这个来自其他人的问题出现在相当多的邮件列表和论坛上,但似乎没有得到答案。
我在 OpenJDK 6 上运行它,所以我得到了源包并将我的调试器步进到库中。它首先查找 jaxb.properties,然后查找系统属性,但均未找到,它尝试使用 com.sun.internal.xml.bind.v2.ContextFactory 创建默认上下文。在那里,异常被抛出(在 ContextFactor.createContext(String ClassLoader, Map)
内),但我看不到发生了什么,因为源不在这里。
预计到达时间:
从ContentFactory的源码来看,发现here ,这可能是一段无法按预期工作的代码:
/**
* Look for jaxb.index file in the specified package and load it's contents
*
* @param pkg package name to search in
* @param classLoader ClassLoader to search in
* @return a List of Class objects to load, null if there weren't any
* @throws IOException if there is an error reading the index file
* @throws JAXBException if there are any errors in the index file
*/
private static List<Class> loadIndexedClasses(String pkg, ClassLoader classLoader) throws IOException, JAXBException {
final String resource = pkg.replace('.', '/') + "/jaxb.index";
final InputStream resourceAsStream = classLoader.getResourceAsStream(resource);
if (resourceAsStream == null) {
return null;
}
来 self 的previous experience ,我猜这与运行它的 OSGi 容器的类加载机制有关。不幸的是,我在这里仍然有点不够深入。
最佳答案
好吧,这花了很多时间,但答案并不令人惊讶,甚至没有那么复杂:
JAXB 找不到 jaxb.index,因为默认情况下,newInstance(String)
使用当前线程的类加载器(由 Thread.getContextClassLoader()
返回)。这在 Felix 中不起作用,因为 OSGi 包和框架的线程具有单独的类加载器。
解决方案是从某个地方获取合适的类加载器并使用 newInstance(String, ClassLoader)
.我从包含 jaxb.index
的包中的一个类中获得了合适的类加载器,出于灵 active 原因,一个明智的选择可能是 ObjectFactory
:
ClassLoader cl = my.package.name.ObjectFactory.class.getClassLoader();
JAXBContext jc = JAXBContext.newInstance("my.package.name", cl);
也许您还可以使用 Bundle
的类加载器。实例正在使用,但我不知道如何使用,上述解决方案对我来说似乎是安全的。
关于java - 为什么在 Apache Felix 中运行时 JAXB 找不到我的 jaxb.index?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1043109/