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.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?
推荐答案
您可以利用 @XmlType
注解来控制对象的创建方式:
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
相关文章