JAXB 2 的 ObjectFactory 类有什么意义? [英] What's the point of JAXB 2's ObjectFactory classes?
问题描述
我是 JAXB 的新手,我使用 JAXB 2.1.3 的 xjc 从我的 XML 模式生成一组类.除了为我的架构中的每个元素生成一个类之外,它还创建了一个 ObjectFactory 类.
I'm new to using JAXB, and I used JAXB 2.1.3's xjc to generate a set of classes from my XML Schema. In addition to generating a class for each element in my schema, it created an ObjectFactory class.
似乎没有什么能阻止我直接实例化元素,例如
There doesn't seem to be anything stopping me from instantiating the elements directly, e.g.
MyElement element = new MyElement();
而教程似乎更喜欢
MyElement element = new ObjectFactory().createMyElement();
如果我查看 ObjectFactory.java,我会看到:
If I look into ObjectFactory.java, I see:
public MyElement createMyElement() {
return new MyElement();
}
那是怎么回事?为什么我还要费心保留 ObjectFactory 类?我假设如果我要从改变的模式重新编译它也会被覆盖.
so what's the deal? Why should I even bother keeping the ObjectFactory class around? I assume it will also be overwritten if I were to re-compile from an altered schema.
推荐答案
向后兼容性并不是唯一的原因.:-P
Backward compatibility isn't the only reason. :-P
对于更复杂的模式,例如对元素内容可以采用的值具有复杂约束的模式,有时您需要创建实际的 JAXBElement
对象.手动创建它们通常并不容易,因此 create*
方法为您完成了繁重的工作.示例(来自 XHTML 1.1 模式):
With more complicated schemas, such as ones that have complicated constraints on the values that an element's contents can take on, sometimes you need to create actual JAXBElement
objects. They are not usually trivial to create by hand, so the create*
methods do the hard work for you. Example (from the XHTML 1.1 schema):
@XmlElementDecl(namespace = "http://www.w3.org/1999/xhtml", name = "style", scope = XhtmlHeadType.class)
public JAXBElement<XhtmlStyleType> createXhtmlHeadTypeStyle(XhtmlStyleType value) {
return new JAXBElement<XhtmlStyleType>(_XhtmlHeadTypeStyle_QNAME, XhtmlStyleType.class, XhtmlHeadType.class, value);
}
这是将 标记转换为
标记的方法:
This is how you get a <style>
tag into a <head>
tag:
ObjectFactory factory = new ObjectFactory();
XhtmlHtmlType html = factory.createXhtmlHtmlType();
XhtmlHeadType head = factory.createXhtmlHeadType();
html.setHead(head);
XhtmlStyleType style = factory.createXhtmlStyleType();
head.getContent().add(factory.createXhtmlHeadTypeStyle(style));
ObjectFactory
的前三种用法可能被认为是多余的(尽管对于一致性很有用),但第四种用法使 JAXB 更容易使用.每次都必须手动编写new JAXBElement
的想象!
The first three uses of the ObjectFactory
could be considered superfluous (though useful for consistency), but the fourth one makes JAXB much, much easier to use. Imaging having to write a new JAXBElement
out by hand each time!
这篇关于JAXB 2 的 ObjectFactory 类有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!