What's the point of JAXB 2's ObjectFactory classes?

Andrew Coleson :

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();

whereas tutorials seem to prefer

MyElement element = new ObjectFactory().createMyElement();

If I look into ObjectFactory.java, I see:

public MyElement createMyElement() {
    return new MyElement();
}

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.

Chris Jester-Young :

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!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related