Skip to content

Combining PojoBuilder and Google AutoValue

Michael Karneim edited this page Apr 5, 2015 · 8 revisions

This is an example that shows how to use PojoBuilder in conjunction with Google AutoValue, which is an immutable value-type code generator for Java.

I have taken the Animal example from the AutoValue page, removed the outer class called Example (just for simplicity), and added the @GeneratePojoBuilder annotation on top of the create method:

@AutoValue
public abstract class Animal {
  @GeneratePojoBuilder
  public static Animal create(String name, int numberOfLegs) {
    return new AutoValue_Animal(name, numberOfLegs);
  }

  abstract String name();

  abstract int numberOfLegs();
}

Optionally, if you rely on PB's copy method feature, you have to make the getter method names match the Java Beans naming convention and rename them like this:

@AutoValue
public abstract class Animal {
  @GeneratePojoBuilder(withCopyMethod = true)
  public static Animal create(String name, int numberOfLegs) {
    return new AutoValue_Animal(name, numberOfLegs);
  }

  abstract String getName();

  abstract int getNumberOfLegs();
}

Finally, you can use the generated builder to create instances of Animal:

  @Test
  public void testCanCreateAnimalUsingBuilder() {
    // Given:
    String name = "dog";
    int numberOfLegs = 4;

    // When:
    Animal act = new AnimalBuilder()
      .withName(name)
      .withNumberOfLegs(numberOfLegs)
    .build();

    // Then:
    assertThat(act.getName()).isEqualTo(name);
    assertThat(act.getNumberOfLegs()).isEqualTo(numberOfLegs);
  }