Intermittent ClassCastException from ElementNSImpl to own type during unmarshalling

℡╲_俬逩灬. 提交于 2019-12-05 05:14:23

I get this exception ONLY when I forget to tell JAXBContext about ALL to-be-marshalled types it could be dealing with.

JAXBContext.newInstance(MyClass1.class,MyClass2.class, [...]);

Neither of the approaches suggested here did it for me. However this resolved my problem

@XmlAnyElement(lax = true)
public List<Foo> foos;

Out of despair we turned to synchronizing on the JAXBContext.class object, seeing this as the only remaining possibility for some race condition and at least we have not been able to reproduce this issue again. Here's the critical code:

synchronized (JAXBContext.class) {
    context = JAXBContext.newInstance(packageList, classLoader);
}

The synchronized clause above resolved the issue for me as well, but it seems like the context should not be a local variable. Instead it should be an instance variable, or a static. I wasn't able to refactor my code how I'd like it, so instead I moved the context into a static initializer, which isn't perfect, but seems to work:

 private static Unmarshaller um;

  static{
    try {
      final JAXBContext ctx = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName());
      um = ctx.createUnmarshaller();
    } catch (final JAXBException e) {
      e.printStackTrace();
    }
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!