JAXB unmarshaller.unmarshal 何时返回 JAXBElement<MySchemaObject>还是一个 MySchemaObject? [英] when does JAXB unmarshaller.unmarshal returns a JAXBElement<MySchemaObject> or a MySchemaObject?
问题描述
我有两个代码,在两个不同的 java 项目中,做几乎相同的事情,(根据 xsd 文件解组 web 服务的输入).
I have two codes, in two different java projects, doing almost the same thing, (unmarshalling the input of a webservice according to an xsd-file).
但在一种情况下我应该这样写:(输入是一个占位符名称)(元素是 OMElement 输入)
But in one case I should write this: (Input is a placeholder name) ( element is OMElement input )
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) 转换只会崩溃:
and in the other lib I must use JAXBElement.getValue(), because it is a JAXBElement that is returned, and a simple (Input) cast simply crashes:
Input input = (Input)unmarshaller.unmarshal( element.getXMLStreamReader() ).getValue();
你知道是什么导致了这种差异吗?
Do you know what leads to such a difference ?
推荐答案
如果根元素唯一对应于一个 Java 类,那么将返回该类的一个实例,否则将返回一个 JAXBElement
被退回.
If the root element uniquely corresponds to a Java class then an instance of that class will be returned, and if not a JAXBElement
will be returned.
如果您想确保始终获得域对象的实例,您可以利用 JAXBInstrospector
.下面是一个例子.
If you want to ensure that you always get an instance of the domain object you can leverage the JAXBInstrospector
. Below is an example.
演示
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
这篇关于JAXB unmarshaller.unmarshal 何时返回 JAXBElement<MySchemaObject>还是一个 MySchemaObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!