Skip to content

Using builders within builders

mkarneim edited this page Dec 7, 2014 · 8 revisions

This is how it looks like to use builders within builders:

Invoice invoice = new InvoiceBuilder()
  .withRecipient(new RecipientBuilder()
    .withName("Sherlock Holmes")
    .withAddress(new AddressBuilder()
      .withStreet("221b Baker Street")
      .withCity("London")
      .withPostCode("NW1 3RX")
    )
  ).build();

This example is taken from Nat Pryce at http://www.natpryce.com/articles/000714.html.

How to do this?

Create a Builder interface with a generic build() method like this:

public interface Builder<P> {
  P build();
}

Then add the following two directives to the @GeneratePojoBuilder annotation:

@GeneratePojoBuilder(
  withBuilderInterface = Builder.class,
  withBuilderProperties = true)
public class Recipient {
  ...

This tells PB that the generated RecipientBuilder should implement the Builder interface, and that it should add with methods for every property which accept Builder instances.

Repeat this for every pojo in your code.

See [Builder.java] (https://github.com/mkarneim/pojobuilder/blob/master/src/testdata/java/samples/Builder.java), [Recipient.java] (https://github.com/mkarneim/pojobuilder/blob/master/src/testdata/java/samples/Recipient.java), and [Address.java] (https://github.com/mkarneim/pojobuilder/blob/master/src/testdata/java/samples/Address.java) for more information.

After that you have the choice to set the pojo's properties using either

  • the concrete value objects
  • or by using builder instances.