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

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

问题描述

我是使用JAXB的新手,我使用JAXB 2.1.3的xjc从我的XML Schema生成一组类。除了为我的模式中的每个元素生成一个类之外,它还创建了一个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);
}

这是你如何获得< style> 标记为< head> 标记:

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更容易使用。成像必须每次手动写出新的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屋!

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