JAXB 2 的 ObjectFactory 类有什么意义? [英] What's the point of JAXB 2's ObjectFactory classes?

查看:32
本文介绍了JAXB 2 的 ObjectFactory 类有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 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);
}

这是将