We use immutable objects all the time. We created Java annotation processors to generate simple, safe and consistent value objects. Do not repeat yourself, try Immutables, the most full-featured and mature tool in this field!
Get started! Read guide... News and announcementsimport org.immutables.value.Value;
// Define abstract value type
@Value.Immutable
public interface ValueObject {
String name();
List<Integer> counts();
Optional<String> description();
}
// Use generated immutable implementation
ValueObject valueObject =
ImmutableValueObject.builder()
.name("My value")
.addCounts(1)
.addCounts(2)
.build();
// Or you can configure different @Value.Style
@Value.Immutable
abstract class AbstractItem {
abstract String getName();
abstract Set<String> getTags();
abstract Optional<String> getDescription();
}
// Use generated value object
Item namelessItem = Item.builder()
.setName("Nameless")
.addTags("important", "relevant")
.setDescription("Description provided")
.build();
Item namedValue = namelessItem.withName("Named");
With Immutables you can generate state of the art immutable object and builder. Type-safe, null-safe and thread-safe, with no boilerplate. Generate builders for immutable objects and even plain static factory methods.
Just add jar to classpath and use. No required runtime dependencies! Guava is supported, but not required. Works out-of-the box with build tools, integrates into IDEs. Get started!
Lazy, derived and optional attributes. Comprehensive support for collections as attributes, including Guava collections. Copy with structural sharing. Strict builders. Singleton and interned instances... and more!
Immutables has much higher standards for code readability than other generators. Generated APIs are carefully tuned for the best power-to-weight ratio. No ugly named identifiers. Implementation code is clear, efficient, and have corresponding javadocs. Take a look
Adapt Immutables to your code conventions and tastes. Customize get, set, with or whatever prefixes. Describe styles as reusable meta-annotations. Generate as much or as little as you need, expose or hide generated classes.
Immutables are serialization ready, including JSON and it's binary forms. Jackson and Gson libraries are supported. Gson is integrated using generated TypeAdapters which use no reflection. JSON guide. MongoDB repositories also included.