I'm afraid, there's no alternative unless you want to switch to something like Scala or are happy with a smaller set of features like those provided by AutoValue.
While AutoValue
is probably the best you can get with pure Java, it offers
- @Getter
- @AllArgsConstructor
- @EqualsAndHashCode
- @ToString
- @Builder
but it misses
- @Wither
- toBuilder
- @Setter
- @Delegate
- @ExtensionMethod
- and some more features I don't use.
While I strongly agree that immutability is a virtue, it sometimes isn't applicable. Anyway, Lombok tries hard to support immutability, it even integrates with Guava's immutable collections, and you can write
@Builder @Getter public final class Sentence {
private final boolean truthValue;
@Singular private final ImmutableList words;
}
and use it like
Sentence s = Sentence.builder().truthValue(true)
.word("Lombok").word("is").word("cool").build();
assertEquals(3, s.getWords().size());
Note: I'm not the author, so I can say it's cool.
For immutables, @Wither
and toBuilder
are pretty cool. The former allows you to create a copy differing by a single field and the latter gives you a builder starting with the current values and suitable for changing multiple fields. The following two lines are equivalent:
o.withA(1).withB(2)
o.toBuilder().a(1).b(2).build()
Both Lombok and AutoValue
use some magic. The magic of the latter is the standard annotation processing, so it's pretty robust. It has some disadvantages as listed on page 27. I'd add the fact that some AutoValue_foo gets generated which I didn't order.
Lombok uses some black magic and thus is much more fragile, but it offers more and works pretty well.