Closed drekbour closed 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.
Looks perfect. Start a cookbook section in the wiki, I'm sure there are other integrations to look into after this one.
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)