我遇到了一个奇怪的错误,当我的代码通过我的程序执行时会发生,但当我在独立的主方法中运行它时不会发生。
代码是:
public static void main(String[] args) throws Exception {
JAXBContext jaxbContext =
JAXBContext.newInstance(ObjectFactory.class);
Marshaller marshaller = jaxbContext.createMarshaller();
JAXBElement<MyTestObject> marshallableSchedule =
new ObjectFactory()
.createMyTestObject(new MyTestObject());
marshaller.marshal(marshallableSchedule, System.out);
}
代码在我的程序中完全相同,但在调用它时出现以下异常:
javax.xml.bind.JAXBException:此上下文已知类 javax.xml.bind.JAXBElement 及其任何父类(super class)。
我还注意到,如果我执行 jaxBContext.toString()
,那么工作示例将显示 ObjectFactory
所在包中的所有类,而失败的示例仅显示 package.ObjectFactory。
我发现了很多像这样的重复问题,但通常说 MyTestObject is notknown,而不是 JAXBElement is notknown。
这与我的项目设置方式有关吗?我正在使用带有功能和插件的 eclipse RCP(如果这有什么不同的话)。我认为这可能是类加载器问题,但我仍然不确定是否是这样或如何修复它。
任何帮助将不胜感激!
最佳答案
ObjectFactory().createMyTestObject(new MyTestObject())
创建的对象是什么类? ObjectFactory
?
声明JAXBContext.newInstance(ObjectFactory.class)
告诉 JAXB 仅考虑此类的实例..
我感觉应该是JAXBContext.newInstance(MyTestObject.class)
...
还有AXBElement<MyTestObject>
仅当类 MyTestObject
时才需要施工对于 JAXB 无效(如果可以的话,添加 `@XmlRootElement 注释)
代码可以是
JAXBContext jaxbContext = JAXBContext.newInstance(MyTestObject.class);
Marshaller marshaller = jaxbContext.createMarshaller();
MyTestObject marshallableSchedule = new MyTestObject();
marshaller.marshal(marshallableSchedule, System.out);
关于java - Eclipse RCP - 程序中的 JAXB 异常,但在最小示例中不存在 : javax. xml.bind.JAXBElement 或其任何父类(super class)在此上下文中已知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41016202/