JAXB-Unmarshalling 期间 ObjectFactory 的作用是什么? [英] What is the ObjectFactory role during JAXB-Unmarshalling?

查看:30
本文介绍了JAXB-Unmarshalling 期间 ObjectFactory 的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 JAXB 2.2.2 来解析一个简单的 XML-REST 流.这是一段代码:

I'm using JAXB 2.2.2 to parse a simple XML-REST stream. This is the piece of code:

JAXBContext jc = JAXBContext.newInstance( "com.example.entities" );
Unmarshaller u = jc.createUnmarshaller();
r = (Response )u.unmarshal( inputStream );

ObjectFactory 类:

ObjectFactory class:

@XmlRegistry
public class ObjectFactory {

    public Response createRsp() {
        return new Response();
    }
}

响应类:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="rsp")
@XmlType
public class Response { ... }

com.example.entities"必须包含 ObjectFactory 类或 jaxb.in​​dex.我想使用 ObjectFactory 类来决定一些 pojo 初始化,但从未使用过这些类:Response 类总是直接由 class.newInstance() 实例化.这有什么问题吗?

The "com.example.entities" must contain the ObjectFactory class or jaxb.index. I would like to use the ObjectFactory class in order to decide some pojo initialization, but these class is never used: the Response class is always instantiated by class.newInstance() directly. Is there something wrong in this?

推荐答案

您可以利用 @XmlType 控制对象创建方式的注解:

You can leverage the @XmlType annotation to control how the objects are created:

@XmlType(factoryClass=ObjectFactory.class, factoryMethod="createRsp")
public class Response {
}

了解更多信息

这篇关于JAXB-Unmarshalling 期间 ObjectFactory 的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆