我有两个代码,在两个不同的 java 项目中,做几乎相同的事情,(根据 xsd 文件解码 web 服务的输入)。
但在一种情况下,我应该这样写:(输入是占位符名称)(元素是 OMElement 输入)
ClassLoader clInput = input.ObjectFactory.class.getClassLoader();
JAXBContext jc = JAXBContext.newInstance("input", clInput);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Input input = (Input)unmarshaller.unmarshal( element.getXMLStreamReader() );
在另一个库中我必须使用 JAXBElement.getValue(),因为它是一个返回的 JAXBElement,并且一个简单的(输入)转换只会崩溃:
Input input = (Input)unmarshaller.unmarshal( element.getXMLStreamReader() ).getValue();
你知道是什么导致了这种差异吗?
最佳答案
如果根元素唯一地对应于一个 Java 类,那么将返回该类的一个实例,如果不是,则返回一个 JAXBElement
。
如果您想确保始终获得域对象的实例,您可以利用 JAXBIntrospector
。下面是一个例子。
演示
package forum10243679;
import java.io.StringReader;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
private static final String XML = "<root/>";
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBIntrospector jaxbIntrospector = jc.createJAXBIntrospector();
Object object = unmarshaller.unmarshal(new StringReader(XML));
System.out.println(object.getClass());
System.out.println(jaxbIntrospector.getValue(object).getClass());
Object jaxbElement = unmarshaller.unmarshal(new StreamSource(new StringReader(XML)), Root.class);
System.out.println(jaxbElement.getClass());
System.out.println(jaxbIntrospector.getValue(jaxbElement).getClass());
}
}
输出
class forum10243679.Root
class forum10243679.Root
class javax.xml.bind.JAXBElement
class forum10243679.Root
关于java - JAXB unmarshaller.unmarshal 何时返回 JAXBElement<MySchemaObject> 或 MySchemaObject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10243679/