Backward compatibility isn't the only reason. :-P
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));
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!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…