Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

MetaBuilder: a builder for builders

DZone's Guide to

MetaBuilder: a builder for builders

· Java Zone
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

The title says it all, MetaBuilder is a builder that let's you create other builders. Dave Masser-Fryehas released this project under the Apache Software License 2.0 at sourceforge, here is the link to the project site. What makes MetaBuilder appart from using the standard Groovy options to make builders is that it follows an schema approach, in other words, you define which properties and the relationships between nodes as you go, in a similar manner as you define an object graph with XML.

Following the example from the documentation, NodeBuilder is a builder created with the standard way (extend BuilderSupport/FactoryBuilderSupport/GroovyObjectSupport or even ObjectGraphBuilder, the usual)

        def nb = new NodeBuilder()

def anInvoice = nb.invoice(date: new Date()) {
items {
item(upc: 123, qty: 1, price: 14.99)
item(upe: 234, qty: 4, price: 14.99)
item(upc: 345, qty: 6, price: 14.99)
}
}

There is a typo in one of the properties of the second item. the code will compile but will either throw an exception or ignore the property value. Either way you will have an incorrect result. Defining the schema with MetaBuilder is pretty straightforward

        import groovytools.builder.*

def mb = new MetaBuilder()
def invoiceSchema = mb.define {
invoice (factory: Invoice) {
properties {
date()
}
collections {
items {
item (factory: Item) {
properties {
upc()
price()
qty()
}
}
}
}
}
}

def anInvoice = mb.build {
invoice(date: new Date()) {
items {
item(upc: 123, qty: 1, price: 14.99)
item(upc: 234, qty: 4, price: 14.99)
item(upc: 345, qty: 6, price: 14.99)
}
}
}
assert(anInvoice instanceof Invoice)

Not only will this code create a graph but it will also use the correct classes for the invoice and item nodes (given that you have an Invoice and an Item class).

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:

Published at DZone with permission of Andres Almiray. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}