AutoValue runs inside javac as a standard annotation processor.
Use Builder when there too many parameters or same type.
@AutoValue
public abstract class Foo {
public static Foo create(String text, int number) {
// defensive copies, preconditions
return new AutoValue_Foo(text, number);
}
public abstract String text(); // or getText(), if you like
public abstract int number();
}
Set a default value for a property
static Builder builder() {
return new AutoValue_Foo.Builder()
.setSomeIntegerField(1).setSomeImmutableSetFeild(ImmutableSet.of());
}
@Nullable properties
toBuilder
AutoValue.Builder
@AutoValue
public abstract class Foo {
static Builder builder() {
return new AutoValue_Foo.Builder();
}
public abstract String text(); // or getText(), if you like
public abstract int number();
@AutoValue.Builder
abstract static class Builder {
abstract Builder text(String value);
abstract Builder number(int value);
abstract Foo build();
}
}
Optional properties
public abstract Optional<String> optionalProperty();
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder SetOptionalProperty(String optionalProperty);
}
autoBuild
@AutoValue.Builder
public abstract static class Builder {
abstract Animal autoBuild();
public Animal build() {
// we can do validation, or normalization, or any other logic here.
return autoBuild();
}
}
Misc
- Use immutable properties.
- We can perform validations at create factory or build method.
- We can write our own equals or hashcode methods.