### Style configuration example Source: https://immutables.github.io/allstyles.html A minimal example of the style annotation configuration. ```java @Value.Style(limitStringLengthInToString = 2) ``` -------------------------------- ### Create Repository Setup Source: https://immutables.github.io/mongo.html Initialize the repository setup using a connection URI or a builder for custom configurations. ```java RepositorySetup setup = RepositorySetup.forUri("mongodb://localhost/test"); ``` ```java MongoClient mongoClient = ... ListeningExecutorService executor = ... GsonBuilder gsonBuilder = new GsonBuilder(); ... RepositorySetup setup = RepositorySetup.builder() .database(mongoClient.getDB("test")) .executor(executor) .gson(gsonBuilder.create()) .build(); ``` -------------------------------- ### Complete Canvas Fixture Example Source: https://immutables.github.io/allstyles.html A comprehensive example demonstrating both covariant return types and builder shortcut initializers in a single configuration. ```java @Value.Style(deepImmutablesDetection = true) public interface Canvas { @Value.Immutable interface Color { @Value.Parameter double red(); @Value.Parameter double green(); @Value.Parameter double blue(); } @Value.Immutable interface Point { @Value.Parameter int x(); @Value.Parameter int y(); } @Value.Immutable interface Line { Color color(); Point start(); Point end(); } } // Usage combining both features: ImmutableLine line = ImmutableLine.builder() .start(1, 2) // Shortcut for .start(ImmutablePoint.of(1, 2)) .end(2, 3) // Shortcut for .end(ImmutablePoint.of(2, 3)) .color(0.9, 0.7, 0.4) // Shortcut for .color(ImmutableColor.of(...)) .build(); // Covariant return types: ImmutablePoint start = line.start(); // Returns ImmutablePoint, not Point ImmutablePoint end = line.end(); // Returns ImmutablePoint, not Point ImmutableColor color = line.color(); // Returns ImmutableColor, not Color ``` -------------------------------- ### Fixture Example for Constructor Builder Source: https://immutables.github.io/allstyles.html A concrete example showing the usage of the 'new' builder style in a fixture class. ```java @Value.Style(builder = "new") // Constructor instead of factory @Value.Immutable interface HaveBuilderNew { int value(); } // Usage: ImmutableHaveBuilderNew instance = new ImmutableHaveBuilderNew.Builder() .value(42) .build(); ``` -------------------------------- ### Configure init with get Pattern Source: https://immutables.github.io/allstyles.html Shows how 'init' interacts with 'get' patterns to strip prefixes from accessors while adding them to builders. ```java @Value.Style( get = {"is*", "get*"}, // Detection: strip "is"/"get" from accessors init = "set*" // Generation: add "set" prefix to builder methods ) @Value.Immutable interface Config { String getName(); // Detected as attribute "name" boolean isEnabled(); // Detected as attribute "enabled" } // Generated builder: ImmutableConfig.builder() .setName("test") // "set" + "name" .setEnabled(true) // "set" + "enabled" .build(); ``` -------------------------------- ### Reference Jakarta Style Source: https://immutables.github.io/allstyles.html Minimal configuration example for enabling jakarta support. ```java @Value.Style(jakarta = true) ``` -------------------------------- ### Fixture example for forceEqualsInWithers Source: https://immutables.github.io/allstyles.html Minimal configuration example for the forceEqualsInWithers style. ```java @Value.Style(forceEqualsInWithers = true) ``` -------------------------------- ### Singleton Pattern Implementation Source: https://immutables.github.io/allstyles.html A complete example of implementing a singleton with a custom accessor name. ```java @Value.Style(instance = "getInstance") @Value.Immutable(singleton = true) interface AppConfig { @Value.Default default String appName() { return "MyApp"; } } // Usage: AppConfig config = ImmutableAppConfig.getInstance(); String name = config.appName(); // "MyApp" ``` -------------------------------- ### Fixture configuration for non-final fields Source: https://immutables.github.io/allstyles.html A minimal style configuration example from the project fixtures. ```java @Value.Style( finalInstanceFields = false, protectedNoargConstructor = true ) ``` -------------------------------- ### Structure multi-module projects Source: https://immutables.github.io/allstyles.html Example of separating API and implementation across different modules. ```java // Module 1: API (com.myapp.api) @Value.Style(packageGenerated = "com.myapp.impl") package com.myapp.api; @Value.Immutable public interface User { String id(); } // Module 2: Implementation (com.myapp.impl) // Contains: com.myapp.impl.ImmutableUser // Module 3: Client (depends only on Module 1) // Can use User interface without seeing ImmutableUser ``` -------------------------------- ### Query DSL Syntax Examples Source: https://immutables.github.io/criteria.html Demonstrates how the DSL maps to SQL-like logic using Disjunctive Normal Form (DNF). ```text // Some examples of Query DSL // left side (DSL) // right side SQL equivalent .fullName.is("John") // fullName = 'John' .fullName.is("John").age.greaterThan(21) // fullName = 'John' AND age > 21 .fullName.is("John").age.greaterThan(21).nickName.isPresent() // fullName = 'John' AND age > 21 AND nickName != null .fullName.is("John").or().fullName.is("Mary") // fullName = 'John' OR fullName = 'Mary' .fullName.is("John").age.greaterThan(21) .or() .fullName.is("Mary") // (fullName = 'John' AND age > 21) OR fullName = 'Mary' .fullName.is("John").age.greaterThan(21) .or() .fullName.is("Mary").age.greaterThan(22) // (fullName = 'John' AND age > 21) OR (fullName = 'Mary' AND age > 22) ``` -------------------------------- ### Common dictionary configurations Source: https://immutables.github.io/allstyles.html Examples for irregular plurals, suppression, and domain-specific terminology. ```java depluralizeDictionary = { "person:people", "child:children", "man:men", "woman:women", "tooth:teeth", "foot:feet", "mouse:mice", "goose:geese" } ``` ```java depluralizeDictionary = { "data:data", // Not "datum" "sheep:sheep", "fish:fish", "series:series", "species:species", "goods", // Short form "news" } ``` ```java depluralizeDictionary = { "index:indices", // Technical: indices, not indexes "vertex:vertices", // Math: vertices "axis:axes", // Geometry: axes "analysis:analyses" // Research: analyses } ``` -------------------------------- ### Implement fluent API with getBuilder Source: https://immutables.github.io/allstyles.html Example of using a custom getBuilder template to create a fluent configuration API. ```java @Value.Style( attributeBuilderDetection = true, getBuilder = "configure*" ) @Value.Immutable interface ServerConfig { DatabaseConfig database(); CacheConfig cache(); } // Fluent configuration: ImmutableServerConfig config = ImmutableServerConfig.builder() .configureDatabase() .host("localhost") .port(5432) .configureCache() .maxSize(1000) .ttlSeconds(300) .build(); ``` -------------------------------- ### Reflection-based framework usage Source: https://immutables.github.io/allstyles.html Example of instantiating an immutable object via reflection. ```java @Value.Style(privateNoargConstructor = true) @Value.Immutable interface ReflectiveBean { String property(); } // Framework can instantiate via reflection: // Constructor ctor = ImmutableReflectiveBean.class.getDeclaredConstructor(); // ctor.setAccessible(true); // Object instance = ctor.newInstance(); ``` -------------------------------- ### Define attributeBuilder patterns Source: https://immutables.github.io/allstyles.html Examples of classes with discoverable builders and a configuration example for the @Value.Style annotation. ```java // Example 1: Type with discoverable builder via static method class MyObject { static Builder builder() { return new Builder(); } static class Builder { public Builder() {} public Builder prop(String value) { return this; } public MyObject build() { return new MyObject(); } } } // Example 2: Type requiring "new" pattern class MyObject { class Builder { public Builder() {} // Requires "new" in attributeBuilder pattern public Builder(MyObject copy) {} MyObject build() { return new MyObject(); } } } @Value.Style( attributeBuilderDetection = true, attributeBuilder = {"builder", "from", "new"} // Customize detection pattern ) ``` -------------------------------- ### Debug-friendly toString Implementation Source: https://immutables.github.io/allstyles.html Example of a custom implementation providing detailed debug information. ```java public class DebugToString { public static String stringify(Object obj) { return String.format("%s@%08x", obj.getClass().getSimpleName(), System.identityHashCode(obj)); } } @Value.Style(delegateToString = "com.debug.DebugToString.stringify") ``` -------------------------------- ### Migrate accessor ordering Source: https://immutables.github.io/allstyles.html Examples comparing old behavior with new options for maintaining or updating ordering after version 2.7.5. ```java // Old code automatically used shallow-first ordering @Value.Immutable interface Product extends BaseProduct { String sku(); } // toString(): Product{sku=ABC123, ...base attributes...} ``` ```java @Value.Style(legacyAccessorOrdering = true) @Value.Immutable interface Product extends BaseProduct { String sku(); } // toString(): Product{sku=ABC123, ...base attributes...} // Same as before! ``` ```java @Value.Immutable interface Product extends BaseProduct { String sku(); } // toString(): Product{...base attributes..., sku=ABC123} // Interface/base attributes first! ``` -------------------------------- ### Configure Jackson Prefix in Build Systems Source: https://immutables.github.io/newandnice.html Examples for configuring the compiler argument in Gradle and Maven when shading Jackson packages. ```gradle // build.gradle with Shadow plugin shadowJar { relocate 'com.fasterxml.jackson', 'com.myapp.shaded.jackson' } tasks.withType(JavaCompile) { options.compilerArgs << '-Aimmutables.jackson.prefix=com.myapp.shaded.jackson' } ``` ```xml -Aimmutables.jackson.prefix=com.myapp.shaded.jackson ``` -------------------------------- ### Configure get and init patterns Source: https://immutables.github.io/allstyles.html Defines custom prefixes for getters and setters to match JavaBean conventions. ```java @Value.Style( get = {"is*", "get*"}, // Detection: strip "is"/"get" init = "set*" // Formatting: add "set" prefix ) @Value.Immutable interface Config { String getName(); // Detected as "name" boolean isEnabled(); // Detected as "enabled" } // Generated builder: ImmutableConfig.builder() .setName("test") // init pattern adds "set" .setEnabled(true) // init pattern adds "set" .build(); ``` -------------------------------- ### Performance-sensitive toString Implementation Source: https://immutables.github.io/allstyles.html Example of a custom implementation optimized for performance. ```java public class FastToString { public static String stringify(Object obj) { // Custom fast implementation, maybe using StringBuilder pool return fastFormat(obj); } } ``` -------------------------------- ### Camel-case handling example Source: https://immutables.github.io/allstyles.html Demonstrates how dictionary matching applies only to the last segment of an attribute name. ```java depluralizeDictionary = {"person:people", "foot:feet"} // Attribute: feetPeople // Last segment: "People" → matches "person:people" → becomes "Person" // Result: feetPerson → addFeetPerson() // Attribute: peopleManagers // Last segment: "Managers" → mechanical "*s" trim → becomes "Manager" // Result: peopleManager → addPeopleManager() ``` -------------------------------- ### Configure getBuilder naming templates Source: https://immutables.github.io/allstyles.html Examples showing default and custom naming templates for nested builder accessors. ```java @Value.Style(attributeBuilderDetection = true) @Value.Immutable interface Container { @Value.Immutable interface Item { String name(); int value(); } Item item(); // Nested immutable } // Generated builder: ImmutableContainer.builder() .itemBuilder() // Gets builder for "item" attribute .name("test") // Build nested Item .value(42) .build(); ``` ```java @Value.Style( attributeBuilderDetection = true, getBuilder = "builderFor*" ) @Value.Immutable interface Container { Item item(); } // Generated method uses custom name: ImmutableContainer.builder() .builderForItem() // Custom name "builderFor" + "Item" .name("test") .value(42) .build(); ``` ```java @Value.Style( attributeBuilderDetection = true, getBuilder = "*NestedBuilder" ) @Value.Immutable interface Container { Item item(); } // Generated: ImmutableContainer.builder() .itemNestedBuilder() // "item" + "NestedBuilder" .name("test") .value(42) .build(); ``` -------------------------------- ### Avoid Guava Dependency Source: https://immutables.github.io/allstyles.html Example of a model definition and configuration that requires no Guava libraries. ```java @Value.Style(jdk9Collections = true) package com.example.model; // No Guava dependency needed @Value.Immutable interface ApiResponse { int statusCode(); List headers(); // JDK 9+ List Map metadata(); // JDK 9+ Map (UNORDERED!) } // pom.xml - No Guava: // // // ``` -------------------------------- ### Common accessor style patterns Source: https://immutables.github.io/allstyles.html Examples of various naming conventions for accessor methods. ```java // JavaBean style (most common): @Value.Style(get = {"is*", "get*"}) // Kotlin/Scala style (no prefix): @Value.Style(get = "*") // Custom prefix: @Value.Style(get = "fetch*") // Multiple custom patterns: @Value.Style(get = {"get*", "is*", "has*", "can*"}) ``` -------------------------------- ### Define a basic encoding class Source: https://immutables.github.io/encoding.html Initial setup for an encoding definition class using the @Encoding annotation. ```java package encoding; import org.immutables.encode.Encoding; @Encoding class TableEncoding { } ``` -------------------------------- ### Using Header Comments for Pragma Directives Source: https://immutables.github.io/allstyles.html Example of using header comments to include pragma directives in generated code. ```java //-no-import-rewrite package com.example; @Value.Style(headerComments = true) @Value.Immutable interface Data { String value(); } // Generated file will include: //-no-import-rewrite // Disable auto-import rewriting for this file ``` -------------------------------- ### Usage example for forceJacksonIgnoreFields Source: https://immutables.github.io/allstyles.html Example of using the style to prevent accidental field serialization. ```java @Value.Style(forceJacksonIgnoreFields = true) @Value.Immutable interface User { String username(); String hashedPassword(); } // Ensures Jackson never accidentally serializes field directly: // Only the accessor methods are used for JSON ``` -------------------------------- ### Instantiate MongoBackend Source: https://immutables.github.io/criteria.html Sets up the MongoDB backend using a database instance and collection resolver. ```java MongoDatabase database = ... // get database (with correct CodecRegistry) MongoBackend backend = new MongoBackend(MongoSetup.of(database)); PersonRepository repository = new PersonRepository(backend); ``` -------------------------------- ### SampleValue with restricted initializer visibility Source: https://immutables.github.io/allstyles.html A minimal example showing an abstract class configured to restrict builder method visibility. ```java @Value.Style(alwaysPublicInitializers = false) @Value.Immutable abstract class SampleValue { public abstract int publicField(); protected abstract int protectedField(); abstract int packagePrivateField(); } ``` -------------------------------- ### Instantiate a Backend Repository Source: https://immutables.github.io/criteria.html General pattern for initializing a repository with a specific backend implementation. ```java Backend backend = ... // can be Mongo / Elasticsearch or any other backend // instantiate repository using existing backend PersonRepository repository = new PersonRepository(backend); ``` -------------------------------- ### Configure generated code location Source: https://immutables.github.io/allstyles.html Examples of organizing generated code into separate packages, hiding implementations, and centralizing output. ```java @Value.Style(packageGenerated = "*.generated") package com.myapp.model; // Abstract types in: com.myapp.model // Generated impl in: com.myapp.model.generated // Clean separation in IDE package view: // com.myapp.model // ├── User.java // ├── Order.java // └── generated/ // ├── ImmutableUser.java // └── ImmutableOrder.java ``` ```java @Value.Style( packageGenerated = "*.impl", visibility = Value.Style.ImplementationVisibility.PACKAGE // Package-private impl ) package com.myapp.api; // Public API: com.myapp.api.User // Hidden impl: com.myapp.api.impl.ImmutableUser (package-private) ``` ```java @Value.Style(packageGenerated = "com.myapp.generated.immutables") package com.myapp.domain.user; @Value.Immutable interface User { String name(); } // All generated classes go to single package: // com.myapp.generated.immutables.ImmutableUser // com.myapp.generated.immutables.ImmutableOrder // com.myapp.generated.immutables.ImmutableProduct ``` -------------------------------- ### Verify canBuild with type name insertion Source: https://immutables.github.io/allstyles.html Example showing the generated method name when using the asterisk wildcard and verifying the builder state. ```java @Value.Style(canBuild = "isBuilder*Ready") // Type name inserted at * @Value.Immutable interface CanBuild { int value(); } // Usage: ImmutableCanBuild.Builder builder = ImmutableCanBuild.builder(); assert !builder.isBuilderCanBuildReady(); // false builder.value(42); assert builder.isBuilderCanBuildReady(); // true ``` -------------------------------- ### Combine Visibility Settings Source: https://immutables.github.io/allstyles.html Demonstrates using both implementation visibility and builder visibility settings together. ```java // Example: Public interface, private implementation, package builder @Value.Style( visibility = Value.Style.ImplementationVisibility.PRIVATE, builderVisibility = Value.Style.BuilderVisibility.PACKAGE ) @Value.Immutable public interface ApiModel { String data(); } // Usage within same package: // - ApiModel is public (interface) // - ImmutableApiModel is private (implementation) // - ImmutableApiModel.Builder is package-private (builder) ``` -------------------------------- ### Serialization framework usage Source: https://immutables.github.io/allstyles.html Example of using privateNoargConstructor with JAXB. ```java @Value.Style(privateNoargConstructor = true) @Value.Immutable @XmlRootElement interface XmlData { String value(); } // JAXB can use private no-arg constructor for deserialization ``` -------------------------------- ### Style annotation for overshadowImplementation Source: https://immutables.github.io/allstyles.html Example of applying the overshadowImplementation style attribute. ```java @Value.Style( overshadowImplementation = true, visibility = Value.Style.ImplementationVisibility.PACKAGE ) ``` -------------------------------- ### Configure Multiple Style Attributes Source: https://immutables.github.io/allstyles.html Demonstrates simultaneous configuration of init, set, and with styles. ```java @Value.Style( init = "set*", // Builder: .setName() set = "put*", // Modifiable: .putName() with = "copyWith*" // Immutable withers: .withName() ) @Value.Immutable @Value.Modifiable interface Person { String name(); } // Builder uses 'init': ImmutablePerson.builder().setName("Alice").build(); // Modifiable uses 'set': ModifiablePerson modifiable = ModifiablePerson.create(); modifiable.putName("Alice"); // Immutable wither uses 'with': ImmutablePerson updated = person.copyWithName("Bob"); ``` -------------------------------- ### Configure deferCollectionAllocation in Style Source: https://immutables.github.io/allstyles.html Example of applying the deferCollectionAllocation style to an immutable interface. ```java @Value.Style(deferCollectionAllocation = true) @Value.Immutable interface Report { String title(); List tags(); // May not be used List warnings(); // May not be used Map metadata(); // May not be used } // If tags/warnings/metadata never populated, no List/Map allocated Report report = ImmutableReport.builder() .title("Summary") .build(); // Only title populated, collections never allocated ``` -------------------------------- ### Example JSON output Source: https://immutables.github.io/json.html The resulting JSON structure from the serialized immutable object. ```json { "a": 1, "b": "B" } ``` -------------------------------- ### Instantiate InMemoryBackend Source: https://immutables.github.io/criteria.html Initializes the dependency-free in-memory backend for local evaluation. ```java // instantiate InMemoryBackend Backend backend = new InMemoryBackend(); ``` -------------------------------- ### Enable legacy ordering via JVM property Source: https://immutables.github.io/allstyles.html Global configuration for legacy ordering using JVM arguments or Maven compiler plugin. ```bash # Enable legacy ordering for entire JVM java -Dorg.immutables.useLegacyAccessorOrdering=true ... ``` ```xml org.apache.maven.plugins maven-compiler-plugin -J-Dorg.immutables.useLegacyAccessorOrdering=true ``` -------------------------------- ### Define and Use Repository Operations Source: https://immutables.github.io/criteria.html Demonstrates how to annotate an interface to generate a repository with RxJava facets and perform basic find and watch operations. ```java // add insert / find / delete / watch operations which return rxjava types @Criteria.Repository(facets = {RxJavaReadable.class, RxJavaWritable.class, RxJavaWatchable.class}) interface Person { } // query datasource and return reactive type: Flowable Flowable persons = repository .find(PersonCriteria.person.age.atLeast(33)) .orderBy(PersonCriteria.person.fullName.asc()) .offset(20) .limit(10) .fetch(); // return rxjava flowable because of RxJavaReadable facet // unbounded stream of events using watch API (if backend supports it) Flowable persons = repository.watcher(PersonCriteria.person.active.isFalse()).watch(); ``` -------------------------------- ### Comparison of builder and newBuilder Source: https://immutables.github.io/allstyles.html Demonstrates how builder and newBuilder control different access points for the generated code. ```java @Value.Style( builder = "newInstance", // Naming for ImmutablePerson.newInstance() newBuilder = "construct" // Naming for Builder.construct() ) @Value.Immutable interface Person { String name(); } // Generated access: ImmutablePerson.Builder builder1 = ImmutablePerson.newInstance(); // Uses 'builder' ImmutablePerson.Builder builder2 = ImmutablePerson.Builder.construct(); // Uses 'newBuilder' ``` -------------------------------- ### Define style via fixture Source: https://immutables.github.io/allstyles.html A minimal example of the @Value.Style annotation applied to a class. ```java @Value.Style(get = {"is*", "get*"}, init = "set*") ``` -------------------------------- ### Instantiate ElasticsearchBackend Source: https://immutables.github.io/criteria.html Initializes the Elasticsearch backend using the low-level REST client. ```java RestClient restClient = ... // provided // use default resolver which maps entity (class) to index name ElasticsearchBackend backend = new ElasticsearchBackend(ElasticsearchSetup.of(restClient)); ``` -------------------------------- ### Use Jackson naming strategy with Immutables Source: https://immutables.github.io/allstyles.html Example of using PropertyNamingStrategies with forceJacksonPropertyNames disabled. ```java @Value.Style( forceJacksonPropertyNames = false, // Let naming strategy work get = {"get*", "is*"} ) @Value.Immutable interface UserData { String getFirstName(); String getLastName(); } // In Jackson configuration: objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); // Results in JSON: // {"first_name": "...", "last_name": "..."} // (instead of {"firstName": "...", "lastName": "..."}) ``` -------------------------------- ### Define Meta-annotation for Style Source: https://immutables.github.io/allstyles.html Shows how to bundle style configurations into a reusable meta-annotation. ```java @Value.Style( get = {"is*", "get*"}, init = "set*", with = "with*" ) @Target({ElementType.PACKAGE, ElementType.TYPE}) @Retention(RetentionPolicy.CLASS) public @interface BeanStyle {} // Apply to all types in package: @BeanStyle package com.example.models; ``` -------------------------------- ### Configure create using constructor Source: https://immutables.github.io/allstyles.html Uses the "new" token to force the generation of a public constructor for modifiable companion classes instead of a factory method. ```java @Value.Style(create = "new") @Value.Immutable @Value.Modifiable interface Config { String value(); } // Uses public constructor: ModifiableConfig config = new ModifiableConfig(); config.setValue("test"); ``` -------------------------------- ### Default behavior of from builder method Source: https://immutables.github.io/allstyles.html Demonstrates the default builder initialization from an existing instance. ```java @Value.Immutable interface Config { String host(); int port(); boolean secure(); } // Generated builder has `from` method: Config template = ImmutableConfig.builder() .host("example.com") .port(8080) .secure(true) .build(); // Initialize new builder from existing instance: Config modified = ImmutableConfig.builder() .from(template) // Copy all values from template .port(8081) // Override just the port .build(); // Result: {host="example.com", port=8081, secure=true} ``` -------------------------------- ### Create a value type for encoding usage Source: https://immutables.github.io/encoding.html Example interface to be used with the custom encoding. ```java package uses; import org.immutables.value.Value; import com.google.common.collect.ImmutableTable; @Value.Immutable interface UseTable { ImmutableTable values(); } ``` -------------------------------- ### Configure custom builder patterns Source: https://immutables.github.io/allstyles.html Demonstrates using custom builder and build method names with attributeBuilderDetection. ```java @Value.Style( attributeBuilderDetection = true, builder = "getTheBuilder", build = "doIIT" ) @Value.Immutable interface Value { FirstPartyImmutable nested(); } ``` -------------------------------- ### JSON representation of generic document Source: https://immutables.github.io/json.html Example JSON structure corresponding to the Doc interface. ```json { "str": { "val": "StringValue" }, "ints": { "val": 124, "description": "Just a number" }, "bool": { "val": true, "description": "Just a boolean" }, } ``` -------------------------------- ### Exclude generated code from coverage Source: https://immutables.github.io/allstyles.html Example of configuring build tools to ignore generated packages. ```java @Value.Style(packageGenerated = "*.generated") package com.example; // Configure build to exclude generated packages from code coverage: // **/generated/** ``` -------------------------------- ### Limitations of 'new' keyword Source: https://immutables.github.io/allstyles.html Examples of configurations that cause compilation errors when using the 'new' keyword. ```java @Value.Style(allParameters = true, of = "new") // Compilation ERROR @Value.Immutable interface Data { String value(); @Value.Check default void validate() { // Validation cannot run in constructor } } ``` ```java @Value.Style(of = "new") // Compilation ERROR @Value.Immutable(singleton = true) interface Config { @Value.Default default String name() { return "default"; } } ``` -------------------------------- ### Instantiate GeodeBackend Source: https://immutables.github.io/criteria.html Initializes the Geode backend using a GemFireCache instance. ```java GemFireCache cache = ... // provided GeodeBackend backend = new GeodeBackend(GeodeSetup.of(cache)); ``` -------------------------------- ### Perform Basic Projections Source: https://immutables.github.io/criteria.html Shows how to use the select operation to project specific fields and map them to a result list. ```java List list = repository .find(person.age.atLeast(33)) .select(person.nickName, person.age) // project two fields of person: nickName and age .map((nickName, age) -> nickName.orElse(null) + " " + (age - 10)) // map operator required after projection. Note that nickName is Optional and age is of type Integer //.map((nickName, age) -> NickNameAndAge::new) // alternative with method reference .fetch(); ``` -------------------------------- ### Generated TypeAdapterFactory Source: https://immutables.github.io/typeadapters.html This is an example of the generated TypeAdapterFactory that handles the serialization and deserialization of the defined immutable types. ```java import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ListMultimap; import com.google.common.collect.SetMultimap; import com.google.gson.*; import com.google.gson.reflect.*; import com.google.gson.stream.*; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import javax.annotation.Generated; import javax.annotation.ParametersAreNonnullByDefault; /** * {@code TypeAdapterFactory} that handle all the immutable types generated under {@code Adapt}. * @see ImmutableAdapt.Inr * @see ImmutableAdapt * @see ImmutableAdapt.Nst */ @SuppressWarnings("all") @Generated({"Gsons.generator", "org.immutables.gson.adapter.Adapt"}) @ParametersAreNonnullByDefault public final class GsonAdaptersAdapt implements TypeAdapterFactory { @SuppressWarnings("unchecked") // safe unchecked, type is verified by type token equality @Override public TypeAdapter create(Gson gson, TypeToken type) { if (InrTypeAdapter.adapts(type)) { return (TypeAdapter) new InrTypeAdapter(gson); } if (AdaptTypeAdapter.adapts(type)) { return (TypeAdapter) new AdaptTypeAdapter(gson); } if (NstTypeAdapter.adapts(type)) { return (TypeAdapter) new NstTypeAdapter(gson); } return null; } @Override public String toString() { return "GsonAdaptersAdapt(Inr, Adapt, Nst)"; } private static class InrTypeAdapter extends TypeAdapter { private static final TypeToken INR_ABSTRACT = TypeToken.get(Adapt.Inr.class); private static final TypeToken INR_IMMUTABLE = TypeToken.get(ImmutableAdapt.Inr.class); private static final TypeToken MAP_SECONDARY_TYPE_TOKEN = new TypeToken() {}; private static final TypeToken LIST_MULTIMAP_SECONDARY_TYPE_TOKEN = new TypeToken() {}; private static final TypeToken SET_MULTIMAP_SECONDARY_TYPE_TOKEN = new TypeToken() {}; private final TypeAdapter mapSecondaryTypeAdapter; private final TypeAdapter listMultimapSecondaryTypeAdapter; private final TypeAdapter setMultimapSecondaryTypeAdapter; InrTypeAdapter(Gson gson) { this.mapSecondaryTypeAdapter = gson.getAdapter(MAP_SECONDARY_TYPE_TOKEN); this.listMultimapSecondaryTypeAdapter = gson.getAdapter(LIST_MULTIMAP_SECONDARY_TYPE_TOKEN); this.setMultimapSecondaryTypeAdapter = gson.getAdapter(SET_MULTIMAP_SECONDARY_TYPE_TOKEN); } static boolean adapts(TypeToken type) { return INR_ABSTRACT.equals(type) || INR_IMMUTABLE.equals(type); } @Override public void write(JsonWriter out, Adapt.Inr value) throws IOException { writeInr(out, value); } @Override public Adapt.Inr read(JsonReader in) throws IOException { return readInr(in); } private void writeInr(JsonWriter out, Adapt.Inr instance) throws IOException { out.beginObject(); String[] arrElements = instance.arr(); if (arrElements.length != 0) { out.name("arr"); out.beginArray(); for (String e : arrElements) { out.value(e); } out.endArray(); } else { out.name("arr"); out.beginArray(); out.endArray(); } List listElements = instance.list(); if (!listElements.isEmpty()) { out.name("list"); out.beginArray(); for (int e : listElements) { out.value(e); } out.endArray(); } else { out.name("list"); out.beginArray(); out.endArray(); } Map mapMapping = instance.map(); if (!mapMapping.isEmpty()) { out.name("map"); out.beginObject(); for (Map.Entry e : mapMapping.entrySet()) { String key = e.getKey(); out.name(key); ``` -------------------------------- ### Default accessor naming patterns Source: https://immutables.github.io/allstyles.html The default behavior strips 'get' prefixes from accessor methods. ```java @Value.Immutable interface Config { String getName(); // → attribute "name" int getPort(); // → attribute "port" boolean enabled(); // → attribute "enabled" (no prefix) } ``` -------------------------------- ### Compare 'from' and 'copyOf' Source: https://immutables.github.io/allstyles.html Use 'from' for partial builder initialization and 'copyOf' for creating complete immutable copies. ```java @Value.Immutable interface Data { String value(); } Data original = ImmutableData.builder().value("test").build(); // Using copyOf (creates complete immutable instance): Data copy1 = ImmutableData.copyOf(original); // Using from (initializes builder, allows modification): Data copy2 = ImmutableData.builder() .from(original) .value("modified") // Can change values .build(); ``` -------------------------------- ### Null pointer exception triggers Source: https://immutables.github.io/allstyles.html Examples of various scenarios where the configured null pointer exception is triggered. ```java @Value.Immutable interface Config { String value(); } ImmutableConfig.builder() .value(null) // Throws throwForNullPointer exception .build(); ``` ```java @Value.Immutable interface Data { List items(); } ImmutableData.builder() .addItems("a", null, "b") // Throws throwForNullPointer exception .build(); ``` ```java @Value.Immutable interface Pair { @Value.Parameter String first(); @Value.Parameter String second(); } ImmutablePair.of(null, "value"); // Throws throwForNullPointer exception ``` ```java @Value.Immutable interface Config { Map properties(); } ImmutableConfig.builder() .putProperties("key", null) // Throws throwForNullPointer exception .build(); ``` -------------------------------- ### Compare isInitialized and canBuild Source: https://immutables.github.io/allstyles.html Illustrates the difference between isInitialized on modifiables and canBuild on builders. ```java @Value.Immutable @Value.Modifiable @Value.Style(canBuild = "canBuild") interface Data { String value(); } // On modifiable: ModifiableData mod = ModifiableData.create(); mod.isInitialized(); // false mod.setValue("test"); mod.isInitialized(); // true mod.toImmutable(); // succeeds // On builder: ImmutableData.Builder builder = ImmutableData.builder(); builder.canBuild(); // false builder.value("test"); builder.canBuild(); // true builder.build(); // succeeds ``` -------------------------------- ### Defining and Configuring a Custom Nullable Annotation Source: https://immutables.github.io/allstyles.html Example of defining a custom annotation and configuring Immutables to recognize it. ```java // Your custom annotation: package com.mycompany.annotations; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) public @interface MayBeNull {} // Configure Immutables to recognize it: @Value.Style(nullableAnnotation = "MayBeNull") @Value.Immutable interface Product { String sku(); @MayBeNull String description(); } ``` -------------------------------- ### Zero-dependency model definition Source: https://immutables.github.io/allstyles.html A complete example of defining an immutable model that results in zero external dependencies. ```java @Value.Style(jdkOnly = true) package com.example.model; import java.util.List; import java.util.Optional; @Value.Immutable interface User { String id(); String name(); Optional email(); List roles(); } // Generated code has ZERO external dependencies beyond JDK ``` -------------------------------- ### Enable and use canBuild Source: https://immutables.github.io/allstyles.html Configures a builder to include a canBuild method and demonstrates checking builder state before calling build. ```java @Value.Style(canBuild = "canBuild") @Value.Immutable interface Config { String host(); // Mandatory int port(); // Mandatory Optional username(); // Optional - not checked @Value.Default boolean ssl() { return true; } // Has default - not checked } // Generated usage: ImmutableConfig.Builder builder = ImmutableConfig.builder(); if (builder.canBuild()) { // false - host and port not set Config config = builder.build(); // Would throw if called } builder.host("localhost"); if (builder.canBuild()) { // still false - port not set builder.build(); } builder.port(8080); if (builder.canBuild()) { // true - all mandatory attributes set Config config = builder.build(); // Safe to call } ``` -------------------------------- ### Expose warnings via Value.Style Source: https://immutables.github.io/allstyles.html Example of disabling warning suppression and allowing specific classpath annotations. ```java @Value.Style( generateSuppressAllWarnings = false, // Expose all warnings allowedClasspathAnnotations = {Override.class} ) ``` -------------------------------- ### Implement custom repositories Source: https://immutables.github.io/criteria.html Manually compose repository functionality using facets. ```java public class MyCustomRepository implements Repository { private final RxJavaReadable readable; public MyCustomRepository(Backend backend) { // open backend session for Person class Backend.Session session = backend.open(Person.class); this.readable = new RxJavaReadable(session); } public Flowable findPeopleOlderThan(Period period) { PersonCriteria criteria = PersonCriteria.person.dateOfBirth.atMost(LocalDate.now().minus(period)); return readable.find(criteria).fetch(); } } ``` -------------------------------- ### Using TYPE_USE nullable annotations Source: https://immutables.github.io/allstyles.html Example of configuring the processor to handle TYPE_USE nullable annotations correctly. ```java import org.checkerframework.checker.nullness.qual.Nullable; @Value.Style( fallbackNullableAnnotation = Nullable.class, passAnnotations = {Nullable.class} ) @Value.Immutable interface Data { @Nullable String value(); // TYPE_USE nullable annotation } // Generated code uses fallback for all internal nullable needs: public @Nullable String value() { ... } ``` -------------------------------- ### Enabling Header Comments Source: https://immutables.github.io/allstyles.html Demonstrates how to enable the feature and the resulting output in the generated file. ```java @Value.Style(headerComments = true) ``` ```java // Source file: Data.java /* * Copyright (C) 2025 Example Corp * Licensed under Apache License 2.0 */ package com.example; @Value.Immutable interface Data { String value(); } // Generated file: ImmutableData.java /* * Copyright (C) 2025 Example Corp * Licensed under Apache License 2.0 */ package com.example; // Header comment copied! @Generated final class ImmutableData implements Data { ... } ``` -------------------------------- ### Compilation error for incompatible types Source: https://immutables.github.io/encoding.html Example of a compilation error when types are not correctly handled by the generated code. ```text [ERROR] ../sample/encoding-use/target/generated-sources/annotations/uses/ImmutableUseTable.java:[156,35] incompatible types: com.google.common.collect.Table cannot be converted to com.google.common.collect.ImmutableTable ``` -------------------------------- ### Example JSON for Polymorphic Deserialization Source: https://immutables.github.io/json.html A JSON structure that can be deserialized into the HostDocument interface defined with polymorphic subtypes. ```json { "values": [ { "number": 2 }, { "string": "Relevant?" }, { "number": 1 }, ] } ``` -------------------------------- ### Perform Aggregation Queries Source: https://immutables.github.io/criteria.html Demonstrates combining groupBy with aggregation operators like max, min, count, and sum. ```java List list = repository.findAll() .orderBy(person.nickName.desc()) .groupBy(person.nickName) .select(person.nickName, person.age.max(), person.age.min(), person.age.count(), person.age.sum()) .map((nickName, max, min, count, sum) -> ("nick=" + nickName.orElse(null) + " max=" + max + " min=" + min + " count=" + count + " sum=" + sum))) .fetch(); ``` -------------------------------- ### Defining a generic immutable value type Source: https://immutables.github.io/json.html Example of an immutable interface using a generic type parameter. ```java @Gson.TypeAdapters @Value.Immutable interface Val { T val(); Optional description(); } ``` -------------------------------- ### Configure from() method behavior Source: https://immutables.github.io/allstyles.html Shows how to rename the from() method and enforce static overloads using the @Value.Style annotation. ```java @Value.Style( from = "populate", // Rename from() method mergeFromSupertypesDynamically = false // Use static overloads ) @Value.Immutable interface Data extends BaseData { String extra(); } // Generated: public Builder populate(Data instance) { ... } public Builder populate(BaseData instance) { ... } ``` -------------------------------- ### Customize accessor naming with JavaBean style Source: https://immutables.github.io/allstyles.html Configure multiple prefixes to handle both 'get' and 'is' accessors. ```java @Value.Style(get = {"is*", "get*"}) // Order matters for matching @Value.Immutable interface Config { String getName(); // → attribute "name" (matches "get*") boolean isEnabled(); // → attribute "enabled" (matches "is*") int port(); // → attribute "port" (no match, used as-is) } // Generated builder: ImmutableConfig.builder() .name("localhost") // Not getName() .enabled(true) // Not isEnabled() .port(8080) // port (unchanged) .build(); ``` -------------------------------- ### Implement common builder usage patterns Source: https://immutables.github.io/allstyles.html Demonstrates template-based creation, incremental modification, and merging attributes from multiple sources. ```java // Pattern 1: Template-based creation Config prodTemplate = ImmutableConfig.builder() .secure(true) .timeout(30) .retries(3) .build(); Config prodServer1 = ImmutableConfig.builder() .from(prodTemplate) .host("server1.example.com") .build(); Config prodServer2 = ImmutableConfig.builder() .from(prodTemplate) .host("server2.example.com") .build(); // Pattern 2: Incremental modification Config config = getBaseConfig(); for (Override override : overrides) { config = ImmutableConfig.builder() .from(config) .apply(override) // Custom method applying override .build(); } // Pattern 3: Merging from multiple sources Result result = ImmutableResult.builder() .from(partialResult1) // Get some attributes .from(partialResult2) // Overwrite/add more attributes .finalValue("computed") .build(); ``` -------------------------------- ### Observe real-time events Source: https://immutables.github.io/criteria.html Use a Watchable facet to observe backend events in real-time. ```java @Criteria.Repository(facets=RxJavaWatchable.class) interface Person {} // if remote database allows filtering in real-time Flowable flow = repository.watcher(PersonCriteria.person.active.isFalse()).watch(); ``` -------------------------------- ### Define Style with Unified Exceptions Source: https://immutables.github.io/allstyles.html Example of a style annotation using a unified custom exception for all validation failures. ```java @Value.Style( strictBuilder = true, throwForInvalidImmutableState = SampleRuntimeException.class, throwForNullPointer = SampleRuntimeException.class ) public @interface SpecifiedExceptionStyle {} ``` -------------------------------- ### Legacy interop configuration Source: https://immutables.github.io/allstyles.html Typical configuration for JavaBean-style legacy interop. ```java @Value.Style( privateNoargConstructor = true, finalInstanceFields = false // Allow mutation after construction ) @Value.Immutable interface LegacyBean { String property(); } // Enables JavaBean-style usage: // 1. Create via no-arg constructor // 2. Set fields via reflection/setters // 3. Use as immutable value after initialization ``` -------------------------------- ### Exception Constructor Requirements Source: https://immutables.github.io/allstyles.html Example of an exception class implementing both the mandatory string constructor and the optional array constructor. ```java public class BuildException extends RuntimeException { // Mandatory: Used by various generators public BuildException(String message) { super(message); } // Optional: Receives missing parameter names public BuildException(String[] missingParams) { super("Build failed. Missing: " + String.join(", ", missingParams)); } } ``` -------------------------------- ### Automatic JDK-only detection in Maven Source: https://immutables.github.io/allstyles.html Example of a pom.xml configuration where Guava is absent, triggering automatic JDK-only mode. ```xml org.immutables value 2.10.0 provided ``` -------------------------------- ### Migrate from Javax to Jakarta Source: https://immutables.github.io/allstyles.html Shows the necessary import changes when transitioning from javax to jakarta namespaces. ```java import javax.validation.constraints.NotNull; import javax.validation.constraints.Min; import javax.annotation.Nullable; @Value.Immutable interface Account { @NotNull String id(); @Min(0) int balance(); @Nullable String notes(); } ``` ```java import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Min; import jakarta.annotation.Nullable; @Value.Style(jakarta = true) @Value.Immutable interface Account { @NotNull String id(); @Min(0) int balance(); @Nullable String notes(); } ``` -------------------------------- ### Mix constructor parameters and builder usage Source: https://immutables.github.io/allstyles.html Demonstrates using both a factory method for required parameters and a builder for complex object construction. ```java @Value.Style(allParameters = true, of = "of") @Value.Immutable interface Person { String name(); int age(); List hobbies(); } // Factory method for required params: Person p1 = ImmutablePerson.of("Alice", 30, List.of()); // Builder for complex construction: Person p2 = ImmutablePerson.builder() .name("Bob") .age(25) .addHobbies("reading", "coding") .build(); ``` -------------------------------- ### Use isInitialized for safe conversion Source: https://immutables.github.io/allstyles.html Example of checking initialization status before converting a modifiable object to an immutable instance. ```java @Value.Immutable @Value.Modifiable interface User { String username(); String email(); Optional displayName(); } ModifiableUser user = ModifiableUser.create(); user.setUsername("alice"); if (user.isInitialized()) { // false - email still missing } user.setEmail("alice@example.com"); if (user.isInitialized()) { // true - all required fields set ImmutableUser immutable = user.toImmutable(); } ``` -------------------------------- ### Custom naming for from method Source: https://immutables.github.io/allstyles.html Shows how to rename the builder initialization method using the from style attribute. ```java @Value.Style(from = "initializeFrom") @Value.Immutable interface Config { String host(); int port(); } // Generated method uses custom name: Config copy = ImmutableConfig.builder() .initializeFrom(template) // Custom method name .port(8081) .build(); ``` -------------------------------- ### Configure allParameters style Source: https://immutables.github.io/allstyles.html Enables a constructor-like factory method for all attributes in an immutable object. ```java @Value.Style( allParameters = true, // Enables constructor of = "create" // Names the factory method ) @Value.Immutable interface User { String id(); String name(); } // Generated: ImmutableUser.create("123", "Alice"); ```