问题描述
我正在使用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.index 。我想使用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?
推荐答案
你可以利用注释控制如何创建对象:
You can leverage the @XmlType
annotation to control how the objects are created:
@XmlType(factoryClass=ObjectFactory.class, factoryMethod="createRsp")
public class Response {
}
更多信息
- http://bdoughan.blogspot.com/2011/06/jaxb-and-factory-methods.html
这篇关于JAXB-Unmarshalling期间的ObjectFactory角色是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!