Implementing Builders with JAXB generated objects

Customising a Builder

Most builders can be generated simply by using <retep:builder/>, however sometimes you will need to modify the default settings. These go into the content of the element and are formed by a set of java Properties.

Getters

The default is not to generate a get method for head set() or add() method. If you want these generated you simply turn on getter generation:

<retep:builder>
  generategetters=true
</retep:builder>

Subclassing and interfaces

You can tell the plugin to have the builder extend some other class and/or implement an interface. In each of these you can use the extendsclass or implementsclass properties.

Note: You can declare one or both of these, but only once for each one. The builder cannot implement multiple interfaces.

<retep:builder>
  extendsclass=com.example.AbstractBuilder
  implementsclass=com.example.SomeInterface
</retep:builder>

If you want to declare generics for these, then the content of the <retep:builder/> element must be wrapped within an XML CDATA section.

Objects referred by a schema but not defined

If you have the case of a schema referring to objects generated outside of this schema, probably by a previous run of the maven-jaxb2-plugin and stored in another artifact, the plugin will assume that it has an associated builder with it.

The Builder will be expected to be located within the same package and have the same name with Builder appended to it.

An example from retepXMPP is the uk.org.retep.xmpp.builder.JID class which has it’s builder uk.org.retep.xmpp.builder.JIDBuilder.

If that Builder class does not exist then javac will fail as it would be expecting it to be present in the classpath.

Further reading

This article only covers the main points of this plugin. There are many more configuration items available to it which can customise the builders even more. Unlike writing this in an article, it’s probably best to look directly at a working example, specifically the jabber:client namespace within retepXMPP.

Although the plugin is complete, there are bound to be the odd bug or two where some combination of how JAXB generates specific classes are not implemented, or it generates a builder which doesn’t work as expected. If you do get one of these then please get in touch, either via XMPP, here or preferably within Jira.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,561 other followers