java - JAXB unmarshaller.unmarshal 何时返回 JAXBElement<MySchemaObject> 或 MySchemaObject?

标签 java jaxb unmarshalling

我有两个代码,在两个不同的 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/

相关文章:

java - 按下 Enter 键时会触发 Vaadin ComboBox 模糊事件

java - 使用 JAXB 从 Java 对象创建 xml 时如何在 JAXB 中创建嵌套根元素

xml - JAXB Unmarshal 创建了一个空对象

java - 来自以 UTF-8 编码的 Java 解码文件的错误字符

java - 将 SOAP 消息解码为 java/或简单地解析 SOAP 消息?

java - 搜索/过滤器的Spring REST API设计

java - 带有发送器的生产者消费者

javascript - 在 java 中安全运行 javascript 代码

java - 如何在 JAXB 中获取输出(编码(marshal)处理)?

java - 在 Weblogic Server 中使用 JAXB 解码