尝试解组 xml 时出现类强制转换异常?

2022-01-19 00:00:00 java jaxb jaxb2

在这里尝试通过类转换异常:

Trying to get past a class cast exception here:

FooClass fooClass = (FooClass ) unmarshaller.unmarshal(inputStream);

抛出此异常:

java.lang.ClassCastException: javax.xml.bind.JAXBElement

我不明白这一点 - 因为该类是由 xjc.bat 工具生成的 - 它生成的类我根本没有改变 - 所以这里应该没有转换问题 - 解组器真的应该给我返回一个可以转换为 FooClass 的类.

I don't understand this - as the class was generated by the xjc.bat tool - and the classes it generated I have not altered at all - so there should be no casting problems here - the unmarshaller should really be giving me back a class that CAN be cast to FooClass.

关于我做错了什么有什么想法吗?

Any ideas as to what I am doing wrong?

推荐答案

FooClassXmlRootElement注解吗?如果没有,请尝试:

Does FooClass have the XmlRootElement annotation? If not, try:

Source source = new StreamSource(inputStream);
JAXBElement<FooClass> root = unmarshaller.unmarshal(source, FooClass.class);
FooClass foo = root.getValue();

这基于 非官方 JAXB 指南.

相关文章