mkarneim / pojobuilder

A Java Code Generator for Pojo Builders
Other
334 stars 44 forks source link

Write cookbook on AutoValue + PojoBuilder #87

Closed drekbour closed 9 years ago

drekbour commented 9 years ago

I think it's definitely worth us taking a look at AutoValue + PojoBuilder and writing a cookbook if it works. AutoValue is reasonably like Lombok but "plays by rules" so is much more likely to work (see #86)

mkarneim commented 9 years ago

Nice tool. I didn't know about it. I just have tried it out, and it works with PB seamlessly.

I have taken the Animal example from the AutoValue page, removed the outer class called Example (just for simplicity), and added the @GeneratePojoBuilder annotation.

@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 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);
  }

This works for both Open JDK and Eclipse compiler.

drekbour commented 9 years ago

Looks perfect. Start a cookbook section in the wiki, I'm sure there are other integrations to look into after this one.

mkarneim commented 9 years ago

See cookbook.