本文介绍了什么时候JAXB unmarshaller.unmarshal返回一个JAXBElement< MySchemaObject>还是MySchemaObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个代码,在两个不同的java项目中,做了几乎相同的事情,(根据xsd文件解组webservice的输入)。

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() );

在另一个lib中我必须使用JAXBElement.getValue(),因为它是一个JAXBElement,返回,简单(输入)转换只是崩溃:

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&lt; MySchemaObject&gt;还是MySchemaObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 19:53