Annotation Type Value.Style
- Enclosing class:
Value
package-info.java). This
annotation more of example of how to define your own styles as meta-annotation rather than a
useful annotation. When using meta-annotation
Be careful to not use keywords or inappropriate characters as parts of naming templates. Some sneaky collisions may only manifest as compilation errors in generated code.
Specific styles will be ignored for a immutable type enclosed with class which is annotated
as @Value.Enclosing. So define styles on the enclosing class.
In this way there will be no issues with the naming and structural conventions
mismatch on enclosing and nested types.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumstatic @interfaceEnables depluralization and may provide depluralization dictionary.static enumIf implementation visibility is more restrictive than visibility of abstract value type, then implementation type will not be exposed as a return type ofbuild()orof()construction methods.static enum -
Optional Element Summary
Optional ElementsModifier and TypeOptional ElementDescriptionAdd value to collection attribute from iterableAdd all values to collection attribute from iterableNaming template for adding a collection of builders.Naming template for adding a new builder instance to a collection.Class<? extends Annotation>[]List of additional annotations to pass through for any jackson json object.booleanIf enabled mandatory attributes would be auto-propagated to be parameters of value object constructor.Class<? extends Annotation>[]Immutables applies some annotations if found on classpath.booleanWhentrue— all settable attributes are considered as they are annotated withValue.Parameter.booleanAll initializers (the methods to set attribute values on a builder) usually have public visibility regardless of the visibility of the attribute accessors.String[]Pattern for detecting builders.booleanWhen enabled: immutable attributes with discoverable builders receive the additional builder API:booleanEnablingattributelessSingletonswitches to old behavior of 2.0.x version when immutable instances which had no attributes defined we automatically generated as singleton havinginstance()accessor.booleanIf enabled, modifiable type will have void setters and will look more like JavaBean.Instance creation method on builder.Builder creator method.Specify the mode in which visibility of generated value type is derived from abstract value type.Specify the mode in which visibility of generated value type is derived from abstract value type.Naming template for thebuildOrThrowmethod which accept exception factory function for throwing in case not all mandatory properties are set.booleanNaming template for thecanBuildmethod on a builder that return boolean if it can "safely" build an object, i.e.Clear all collection attributes and unset(or other container).booleanWhen enabled:clearmethod will be generated on builder to reset state of a builder.Copy constructor method name.Factory method for modifiable implementation, could be "new" to create objects using constructor.booleanDeep analysis of immutable types enables additional convenience features.booleanThis funny-named named attribute, when enabled makes default accessor methods defined in interfaces/traits behave as if they annotated as @Value.Default.Specify default options for the generated immutable objects.booleanWhen this optimisation in enabled then the processor tries to defer allocation of collection in builder and modifiable objects.DelegatestoStringimplementation completely to a fully qualified path to a method name, exampledelegateToString="com.whatever.packg.ToStringer.stringify".booleanString[]Dictionary of exceptions — array of "singular:plural" pairs as alternative to mechanical "*s" depluralization.Class<? extends Annotation> For many cases of nullable annotation is just copied to generated code when recognized (by simple name, seenullableAnnotation()).booleanDisable final fields only if there are no other way, considered unsafe.booleanIfforceEqualsInWithersenabled, generated with-copy methods will have equality check forced.booleanbooleanAs there are some ambiguities with how certain field prefixes work ("get", "is") we by default force whatever is inferred by Immutables.Method to initialize builder with values from instance.booleanGenerateSuppressWarnings("all")in generated code.String[]Patterns to recognize accessors.Naming template for retrieving a nested builder.Naming template for retrieving an immutable list of builders.booleanEnable if you needed to copy header comments from an originating source file with abstract types to generated (derived) implementation classes.Class<?>[]You can provide classes which must contain copyOf method with relevant overloads which should not have ambiguous cases as it will be fully a subject to JLS rules of static imports and compile time overload resolution.booleanBy default builder is generated as inner builder class nested in immutable value class.IfincludeHashCodeis not empty it will be used as part of generated `hashCode`.Builder initialization method.Singleton accessor method nameMethod to determine if all required attributes are set.Method to determine if attribute is setbooleanSetting this tofalsewould disable any special jackson integration capabilities.booleanIf enabled,jakarta.*packages will take over any relevantjavax.*.booleanbooleanWhentrue— forces to generate code which use only JDK 7+ standard library classes.intSetting to trim strings longer than a defined length when calling the toString method.Builder creator method, it differs frombuilder()in that this naming is used for builders that are external to immutable objects, such as top level builders for values or factories.Immutables recognizes nullable annotation by simple name.Constructor method name.booleanSpecify whether init, copy and factory methods and constructors for an unwrappedXofOptional<X>should acceptnullvalues as empty value.booleanMakes abstract value type predominantly used in generated signatures rather than immutable implementation class.Naming templatepackageGeneratedused to derive name of the package where the annotation processor should put generated classes for corresponding immutable values.Class<? extends Annotation>[]List type of annotations to copy over from abstract value type to immutable implementation class.booleanGenerate a private no-argument constructor in generated code.booleanGenerate a protected no-argument constructor, mainly for reflective usage by advanced toolkits.Puts entry to a map attributePuts all entries to a map attributeString to substitute value of the attribute in a generatedtoStringimplementation whenValue.Redactedannotation is applied to the attribute.Modifiable object "setter" method.Naming template for setting a nested builder.booleanStaged (aka telescopic) builders are a special flavor of builders which provides compile-time safety to a staged building.booleanWhentrue— forces to generate strict builder code.booleanStrict modifiable will refuse any accessor value (by throwingIllegalStateException) which is mandatory.Class<? extends RuntimeException> Runtime exception to throw when an immutable object is in an invalid state.Class<? extends RuntimeException> Runtime exception to throw when null reference is passed to non-nullable parameter or occured in array/container that must not contain nulls.Naming template for thetoBuildermethod on a immutable instance that returns new builder on which merge method is already called on this instancebuilder.from(this).Method to convert to instance of modifiable type to "canonical" immutable instance.booleanWhentransientDerivedFieldsis enabled (as it by default), the backing fields for derived attributes will be marked astransient(unless type isSerializableby using regular Java serialization (not for when structural serialization is on via @Serial.Structural).String[]Naming templates to detect base/raw type name from provided abstract value type name.Generated builder class name.Name template to generate immutable implementation type by using base/raw type name.Umbrella nesting class name generated usingValue.Enclosing.Immutable class name when generated under umbrella class usingValue.Enclosingannotation.Inner builder class name which will be matched to be extend/super for generated builder.Inner builder class name which will be matched to be extend/super for generated Modifiable class.Modifiable companion class name templateGenerated "with" interface name.Detects and use method named as specified to customize generatedhashCode.booleanAs of 2.1 we are switching to safe generation of derived and default values when there are more than one such attribute.Unset attribute method.Whentrue— disables check that all required attributes have been provided to a builder.Specify the mode in which visibility of generated value type is derived from abstract value type.Specify the mode in which visibility of generated value type is derived from abstract value type.booleanWhenweakInterningis enabled, then for value types with @Value.Immutable(intern=true)weak (seeWeakReference) interning will be used.Modify-by-copy "with" method.Modify-by-copy method which receivesUnaryOperatorto transform an attribute before constructing a copy of immutable object.
-
Element Details
-
get
String[] getPatterns to recognize accessors. For exampleget = {"is*", "get*"}will mimick style of bean getters. If none specified or if none matches, then raw accessor name will be taken literally.By default, only
get*prefix is recognized, along with falling back to use accessor name literally. It is up to you if you want to use "get" prefixes or not. Original author is leaning towards not using noisy prefixes for attributes in immutable objects, drawing similarity with annotation attributes, however usage of "get" is neither recommended, nor discouraged.This is detection pattern, not formatting pattern. It defines how to recognize name, not how to derive name
- Returns:
- naming template
- Default:
{"get*"}
-
init
String initBuilder initialization method. i.e. "setter" in builder. Do not confuse withset()- Returns:
- naming template
- Default:
"*"
-
with
String withModify-by-copy "with" method.- Returns:
- naming template
- See Also:
- Default:
"with*"
-
withUnaryOperator
String withUnaryOperatorModify-by-copy method which receivesUnaryOperatorto transform an attribute before constructing a copy of immutable object. This feature is disabled by default, unless you specify a naming template for this method. A template can be something like"with*Mapped","update*", or"transform*"– the choice is yours. Can even be"with*"or"*"in hope there will be no overload collisions.Unary operator transforms values, optional values and collection elements. (currently JDK Optional only, use Encodings for custom optional and containers).
- Returns:
- naming template. By default, it is empty and feature is disabled.
- Default:
""
-
add
String addAdd value to collection attribute from iterable- Returns:
- naming template
- Default:
"add*"
-
addAll
String addAllAdd all values to collection attribute from iterable- Returns:
- naming template
- Default:
"addAll*"
-
put
String putPuts entry to a map attribute- Returns:
- naming template
- Default:
"put*"
-
putAll
String putAllPuts all entries to a map attribute- Returns:
- naming template
- Default:
"putAll*"
-
copyOf
String copyOfCopy constructor method name.- Returns:
- naming template
- Default:
"copyOf"
-
of
String ofConstructor method name.Since version
2.1.5you can also use "new" template string to generate public constructor instead of factory. The public constructor functionality is experimental. Note that having public constructor configured will not work ifValue.CheckorValue.Immutable.singleton()is used and certain other functionality. In such cases compile error would be raised.- Returns:
- naming template
- Default:
"of"
-
instance
String instanceSingleton accessor method name- Returns:
- naming template
- Default:
"of"
-
builder
String builderBuilder creator method. This naming allow special keyword "new" value. This will customize builder to be created using constructor rather than factory method.- Returns:
- naming template
- See Also:
- Default:
"builder"
-
newBuilder
String newBuilderBuilder creator method, it differs frombuilder()in that this naming is used for builders that are external to immutable objects, such as top level builders for values or factories. This naming allow special keyword "new" value, which is the default. "new" will customize builder to be created using constructor rather than factory method.- Returns:
- naming template
- See Also:
- Default:
"new"
-
from
String fromMethod to initialize builder with values from instance. Can be set to empty string to disable "from" method generation.- Returns:
- naming template
- Default:
"from"
-
build
String buildInstance creation method on builder.- Returns:
- naming template
- Default:
"build"
-
buildOrThrow
String buildOrThrowNaming template for thebuildOrThrowmethod which accept exception factory function for throwing in case not all mandatory properties are set. Non-default (i.e. not empty) template will essentially enable generation of this method, acting both as a naming template and as a feature flag.Generation of build or throws method requires presence of a function type on the classpath, provided either by Java 8 or Guava on Java 7. If used on java 7 without Guava, this style will have no effect: no method will be generated.
Note: This attribute-style is experimental and may be changed in near releases. You should not rely on it if don't ready to change code on minor updates of the annotation processor
- Returns:
- naming template, if default/empty it will not be generated
- Default:
""
-
canBuild
String canBuildNaming template for thecanBuildmethod on a builder that return boolean if it can "safely" build an object, i.e. all attributes are set and instance would be returned by calling.build()method without throwingIllegalStateException. Note: By default this method is not generated, unless a naming is provided. For example, set it tocanBuild="canBuild"andboolean canBuild()method will be generated on builder. Note: when using encoding, building of attributes is delegated to encoding specific routines, so that general builder infrastructure may not know if attribute can be safely constructed, in this case, canBuild method might give wrong answer.- Returns:
- naming template, if default/empty it will not be generated
- Default:
""
-
toBuilder
String toBuilderNaming template for thetoBuildermethod on a immutable instance that returns new builder on which merge method is already called on this instancebuilder.from(this). By default, this naming template is empty, and this method is not generated. To enable generation of this method, you must specify naming template,(toBuilder="toBuilder"). Naming template can insert type name for an asterisk, but in most cases you would just use method name verbatim.Note: This attribute-style is experimental and may be changed in near releases. This is not compatible with strict builders and will not be generated if
strictBuilder()istrue. Also, when enabled, this will not be considered an attribute if defined asabstract Builder toBuilder()in abstract value type.- Returns:
- naming template, if default/empty it will not be generated
- Default:
""
-
underrideHashCode
String underrideHashCodeDetects and use method named as specified to customize generatedhashCode. Abstract value types defined as interfaces cannot implementdefaultmethods ofjava.lang.Object, such asObject.hashCode()implemented asdefaultinterface methods and so cannot override (actually "underride" if that is the right term) the defaulthashCodewhich is generated on immutable implementation. So in order to customize and replace default generated code, you can now declaredefaultorstaticmethod named, sayhash(underwriteInterfaceHashCode="hash"), will be used in generatedhashCodemethod. The signature of thedefault/staticshould be compatible to the ones ofObject, static methods suppose to take instances of the abstract value type as parameter instead of a plainObject.Wiring of the custom method will only occur if found by the name and matched by signature.
- Returns:
- method name, if empty (the
default) it will not be detected and wired in generation.
- Default:
""
-
underrideEquals
String underrideEquals- Default:
""
-
underrideToString
String underrideToString- Default:
""
-
delegateToString
String delegateToStringDelegatestoStringimplementation completely to a fully qualified path to a method name, exampledelegateToString="com.whatever.packg.ToStringer.stringify". The path will be used literally in generated code, and a single parameter will be passed to it,thisimmutable object instance.Note: If specified, it will take precedence over any other
toStringcustomization mechanism- Returns:
- fully qualified static method name, if empty (by default) will not be used
- Default:
""
-
includeHashCode
String includeHashCodeIfincludeHashCodeis not empty it will be used as part of generated `hashCode`. This will be a verbatim line of code used with the tag-placeholder[[type]]will be replaced with the simple (or relative to top level) name of the abstract value type. It's the responsibility of the user to put well-formed code to be put in context, including parenthesis, etc. use try-see-fix approach here. Other fields will be included as usual, coming after this custom value.Examples might give you better ideas how to use it:
includeHashCode = "this.baseHashCode()" includeHashCode = "super.hashCode()" includeHashCode = "getClass().hashCode()" includeHashCode = "[[type]].class.hashCode()" includeHashCode = "(\"[[type]]\".length() + 1)"
Note: this will be ignored if `hashCode` will be manually written in the abstract value class or
underrideHashCode()will be used for the same purpose- Returns:
- interpolated code snippet, by default empty and have no effect
- Default:
""
-
isInitialized
String isInitializedMethod to determine if all required attributes are set. Default method name choice for this is mostly random.- Returns:
- naming template
- Default:
"isInitialized"
-
isSet
String isSetMethod to determine if attribute is set- Returns:
- naming template
- Default:
"*IsSet"
-
set
String setModifiable object "setter" method. Used for mutable implementations. Do not confuse withinit()- Returns:
- naming template
- Default:
"set*"
-
unset
String unsetUnset attribute method. Used for mutable implementations.- Returns:
- naming template
- Default:
"unset*"
-
clear
String clearClear all collection attributes and unset(or other container). Used for mutable implementations.- Returns:
- naming template
- Default:
"clear"
-
create
String createFactory method for modifiable implementation, could be "new" to create objects using constructor.- Returns:
- naming template
- Default:
"create"
-
toImmutable
String toImmutableMethod to convert to instance of modifiable type to "canonical" immutable instance.- Returns:
- naming template
- Default:
"toImmutable"
-
typeBuilder
String typeBuilderGenerated builder class name.- Returns:
- naming template
- Default:
"Builder"
-
typeInnerBuilder
String typeInnerBuilderInner builder class name which will be matched to be extend/super for generated builder.- Returns:
- naming template
- Default:
"Builder"
-
typeAbstract
String[] typeAbstractNaming templates to detect base/raw type name from provided abstract value type name. If none specified or if none matches, then raw type name will be taken literally the same as abstract value type name.This is detection pattern, not formatting pattern. It defines how to recognize name, not how to derive name
- Returns:
- naming templates
- Default:
{"Abstract*"}
-
typeImmutable
String typeImmutableName template to generate immutable implementation type by using base/raw type name. UsetypeAbstract()to customize base/raw name inference.- Returns:
- naming template
- Default:
"Immutable*"
-
typeImmutableEnclosing
String typeImmutableEnclosingUmbrella nesting class name generated usingValue.Enclosing.- Returns:
- naming template
- Default:
"Immutable*"
-
typeImmutableNested
String typeImmutableNestedImmutable class name when generated under umbrella class usingValue.Enclosingannotation.- Returns:
- naming template
- See Also:
- Default:
"*"
-
typeModifiable
String typeModifiableModifiable companion class name template- Returns:
- naming template
- Default:
"Modifiable*"
-
typeInnerModifiable
String typeInnerModifiableInner builder class name which will be matched to be extend/super for generated Modifiable class.- Returns:
- naming template
- Default:
"Modifiable"
-
typeWith
String typeWithGenerated "with" interface name. Used to detect a demand and generate "with" interface.- Returns:
- naming template
- Default:
"With*"
-
packageGenerated
String packageGeneratedNaming template
packageGeneratedused to derive name of the package where the annotation processor should put generated classes for corresponding immutable values. By default it equals to"*"which means to use the same package as abstract value type. It can be configured to a specific package name, like"com.acme.specific", or used to specify pattern, like "*.gen" or "*.immutable.impl".Note: It is expected that most generators will honor this style attribute, but it's not guaranteed. When you generate derived classes in the same package (by default), then implementation could access and/or override package-private methods. If using a different package make sure to use public or protected access where needed, otherwise illegal access compilation errors will be flagged in the generated code.
- Returns:
- generated package naming template
- Default:
"*"
-
defaults
Value.Immutable defaultsSpecify default options for the generated immutable objects. If at least one attribute is specified in inline @Value.Immutableannotation, then this default will not be taken into account, objects will be generated using attributes from inline annotation.- Returns:
- default configuration
- Default:
@org.immutables.value.Value.Immutable
-
jdkOnly
boolean jdkOnlyWhentrue— forces to generate code which use only JDK 7+ standard library classes. It isfalseby default, however usage of JDK-only classes will be turned on automatically if Google Guava library is not found in classpath. The generated code will have subtle differences, but nevertheless will be functionally equivalent.Note that some additional annotation processors (for example mongo repository generator) may not work without Guava being accessible to the generated classes, and thus will not honor this attribute
- Returns:
- if forced JDK-only class usage
- Default:
false
-
jdk9Collections
boolean jdk9CollectionsWhentrue— will use JDK 9+ immutable collections to implementList/Set/Mapattributes. In JDK 9+, immutable collections are instantiated viaof/copyOfstatic methods onList,Set,Mapinterfaces:List.of(),Set.copyOf(Collection), etc. Please note that these collections do not supportnullelements, also Sets and Maps do not maintain insertion order, so the order is arbitrary and cannot be relied upon.- Returns:
- if
trueuse JDK 9+ immutableList,Set, orMap
- Default:
false
-
strictBuilder
boolean strictBuilderWhentrue— forces to generate strict builder code. Strict builders are forward only. For collections and maps, there's no set/reset methods are generated in favor of using additive only initializers. For regular attributes, initializers could be called only once, subsequent reinitialization with throw exception. Also, "from" method (named byfrom()) will not be generated on builder: it becomes error-inviting to reinitialize builder values.NullableandDefaultcontainer attributes are not supported whenstrictBuilder = true.Usage of strict builders helps to prevent initialization mistakes early on.
- Returns:
- if strict builder enabled
- Default:
false
-
strictModifiable
boolean strictModifiableStrict modifiable will refuse any accessor value (by throwingIllegalStateException) which is mandatory. Enabled by default. Set it tofalseand it will allow to get current field value even if not initialized (nullfor references,0,false— for primitives).- Returns:
- default is
true, enabling strict modifiable
- Default:
true
-
validationMethod
Value.Style.ValidationMethod validationMethodWhentrue— disables check that all required attributes have been provided to a builder.- Default:
SIMPLE
-
allParameters
boolean allParametersWhen
true— all settable attributes are considered as they are annotated withValue.Parameter. UseValue.Parameter(false)annotation on an attribute to cancel the effect ofallParameters = true.This style could be used to create special tuple-style annotations:
@Value.Style( typeImmutable = "*Tuple", allParameters = true, defaults = @Value.Immutable(builder = false)) public @interface Tuple {} @Tuple @Value.Immutable interface Color { int red(); int green(); int blue(); @Value.Parameter(false) ListauxiliaryInfo(); } ColorTuple.of(0xFF, 0x00, 0xFE); - Returns:
- if all attributes will be considered parameters
- Default:
false
-
defaultAsDefault
boolean defaultAsDefaultThis funny-named named attribute, when enabled makes default accessor methods defined in interfaces/traits behave as if they annotated as @Value.Default. This is not a default behaviour to preserve compatibility and also to have a choice to not opt-in for this new functionality when not needed.- Returns:
- if consider default method accessors as @
Value.Default
- Default:
false
-
headerComments
boolean headerCommentsEnable if you needed to copy header comments from an originating source file with abstract types to generated (derived) implementation classes. Header comments are comments preceeding package declaration statement. It could be used to copy license headers or even special pragma comments (such as//-no-import-rewrite). It is off by default because not often needed (as generated files are transient and not stored in version control), but adds up to the processing time.- Returns:
- if copy header comments to generated classes.
- Default:
false
-
passAnnotations
Class<? extends Annotation>[] passAnnotationsList type of annotations to copy over from abstract value type to immutable implementation class. Very often this functionality is not needed when annotations are declared asInherited, but there are cases where you need to pass specific non-inherited annotations to the implementation class. In general, copying all type-level annotations is not very safe for annotation processing and some other annotation consumers. By default, no annotations are copied unless you specify non-empty annotation type list as value forpassAnnotationsattribute. However there are some special annotations which are copied using special logic, such asNullableannotations (and Jackson annotations)This style parameter is experimental and may change in future.
- Returns:
- types of annotations to pass to an immutable implementation class and its attributes.
- Default:
{}
-
additionalJsonAnnotations
Class<? extends Annotation>[] additionalJsonAnnotationsList of additional annotations to pass through for any jackson json object. Soft-deprecated this is no longer necessary.- Returns:
- types of annotations to pass to the json methods on an immutable implementation class
- Default:
{}
-
visibility
Value.Style.ImplementationVisibility visibilitySpecify the mode in which visibility of generated value type is derived from abstract value type. It is a good idea to not specify such attributes inline with immutable values, but rather create style annotation (@see Style).- Returns:
- implementation visibility
- Default:
SAME
-
visibilityString
String visibilityStringSpecify the mode in which visibility of generated value type is derived from abstract value type. Specifying this will overridevisibility()and the reason why this option as a string exists, is to avoid javac warnings mentioned in #291.- Returns:
- implementation visibility as string
- Default:
""
-
optionalAcceptNullable
boolean optionalAcceptNullableSpecify whether init, copy and factory methods and constructors for an unwrappedXofOptional<X>should acceptnullvalues as empty value. By default nulls are rejected in favor of explicit conversion usingOptional.ofNullable. Please note that initializers that take explicitOptionalvalue always reject nulls regardless of this setting.- Returns:
- optional elements accept nullables
- Default:
false
-
generateSuppressAllWarnings
boolean generateSuppressAllWarningsGenerateSuppressWarnings("all")in generated code. Set this tofalseto expose all warnings in a generated code. To suppress other warnings issued by Immutables use explicit annotations @SuppressWarning("immutables")or @SuppressWarning("all")- Returns:
trueif will generate suppress all warnings, enabled by default.
- Default:
true
-
privateNoargConstructor
boolean privateNoargConstructorGenerate a private no-argument constructor in generated code. Note that this property will be ignored ifValue.Immutable.singleton()returnstrue.- Returns:
trueif will generate a default no argument constructor, disabled by default.
- Default:
false
-
protectedNoargConstructor
boolean protectedNoargConstructorGenerate a protected no-argument constructor, mainly for reflective usage by advanced toolkits. Note that this one overridesprivateNoargConstructor()if both are set totrue. This property will be ignored ifValue.Immutable.singleton()returnstrue.- Returns:
trueif will generate a no argument constructor with protected visibility, disabled by default.
- Default:
false
-
attributelessSingleton
boolean attributelessSingletonEnablingattributelessSingletonswitches to old behavior of 2.0.x version when immutable instances which had no attributes defined we automatically generated as singleton havinginstance()accessor. As of 2.1 we are more strict and explicit with singletons and are not generating it by default, only whenValue.Immutable.singleton()is explicitly enabled.- Returns:
trueif auto singleton on new attributes (default isfalse)
- Default:
false
-
unsafeDefaultAndDerived
boolean unsafeDefaultAndDerivedAs of 2.1 we are switching to safe generation of derived and default values when there are more than one such attribute. ThisunsafeDefaultAndDerivedstyle could be enabled to revert to old, unsafe behavior.In order to initialize default and derived attributes method bodies (initializers) will be invoked. Initializers could refer to other attributes, some of which might be also derived or uninitialized default values. As it's extremely difficult to reliably inspect initializer methods bodies and compute proper ordering, we use some special generated code which figures it out in runtime. If there will be a cycle in initializers, then
IllegalStateExceptionwill be thrown.If you set
unsafeDefaultAndDerivedtotrue, then simpler, unsafe code will be generated. With the unsafe code you cannot refer to other default or derived attributes in initializers as otherwise result will be undefined as order of initialization is not guaranteed.- Returns:
trueif old unsafe (but potentially with less overhead) generation should be used.
- Default:
false
-
clearBuilder
boolean clearBuilderWhen enabled:clearmethod will be generated on builder to reset state of a builder. Primarily designed for resource constrained environments to minimize allocations. This functionality is disabled by default as usually it's better to create fresh builders with a clean state: in server side java it may be more efficient to allocate new builder than clean previously allocated one.Note: this functionality is experimental and may be changed in further versions
- Returns:
trueif clean method would be generated.- See Also:
- Default:
false
-
deferCollectionAllocation
boolean deferCollectionAllocationWhen this optimisation in enabled then the processor tries to defer allocation of collection in builder and modifiable objects. The resulting code might somewhat be slower at a microbenchmark scale due to additional "if" checks, but might save some allocations. Does not work whenstrictBuilder()is enabled. Disabled by default.- Returns:
trueif defer collection allocation.
- Default:
false
-
deepImmutablesDetection
boolean deepImmutablesDetectionDeep analysis of immutable types enables additional convenience features. When enabled, each attribute is analyzed and if it is discovered to be an @Value.Immutableobject (either abstract value type or generated implementation type), then some special handling will be applied to it. As of now following functionality is applied:- Accessors in a generated immutable type will be implemented with a covariant return type of the immutable implementation of the abstract value type of the declared attribute. This has no effect on the collection/container attributes to not interfere with invariant generic types. Derived and Default attributes are also not supported as of now to avoid excessive complexity
- Builder initializers will have overloaded variants with parameters of the attribute value object's constructor (if it has constructor as opposed to the ones which only have builder). Effectively this is a shortcut to initialize value object in a more concise way. This works for regular and collection attributes (but not for maps or arrays to avoid complex and confusing overload).
@Value.Style(deepImmutablesDetection = true) public interface Canvas { @Value.Immutable public interface Color { @Value.Parameter double red(); @Value.Parameter double green(); @Value.Parameter double blue(); } @Value.Immutable public interface Point { @Value.Parameter int x(); @Value.Parameter int y(); } @Value.Immutable public interface Line { Color color(); Point start(); Point end(); } public static void main(String... args) { ImmutableLine line = ImmutableLine.builder() .start(1, 2) // overload, equivalent of .start(ImmutablePoint.of(1, 2)) .end(2, 3) // overload, equivalent of .end(ImmutablePoint.of(2, 3)) .color(0.9, 0.7, 0.4) // overload, equivalent of .color(ImmutableColor.of(0.9, 0.7. 0.4)) .build(); ImmutablePoint start = line.start(); // return type is ImmutablePoint rather than declared Point ImmutablePoint end = line.end(); // return type is ImmutablePoint rather than declared Point ImmutableColor color = line.color(); // return type is ImmutableColor rather than declared Color ImmutableLine.builder() .start(start) .end(end) .color(color) .build(); } }Disabled by default as, speculatively, this might increase processing time. It will not work for yet-to-be-generated types as attribute types, which allows only shallow analysis.
Note: this functionality is experimental and may be changed in further versions. As of version 2.2 we no longer add
*Ofsuffix to the shortcut initializer attribute.- Returns:
trueif deep detection is enabled.
- Default:
false
-
overshadowImplementation
boolean overshadowImplementationMakes abstract value type predominantly used in generated signatures rather than immutable implementation class. In case ofvisibility()is more restrictive thanbuilderVisibility()(for example isPRIVATE), then this feature is turned on automatically.Note: not all generators or generation modes might honor this attribute
- Returns:
trueif methods of generated builders and other classes should return abstract type, rather than work with immutable implementation class.
- Default:
false
-
implementationNestedInBuilder
boolean implementationNestedInBuilderBy default builder is generated as inner builder class nested in immutable value class. Setting this totruewill flip the picture — immutable implementation class will be nested inside builder, which will be top level class. In case ifvisibility()is set toValue.Style.ImplementationVisibility.PRIVATEthis feature is turned on automatically.- Returns:
trueif builder should be generated as top level class and implementation will became static inner class inside builder.
- Default:
false
-
forceJacksonPropertyNames
boolean forceJacksonPropertyNamesAs there are some ambiguities with how certain field prefixes work ("get", "is") we by default force whatever is inferred by Immutables. Disable forcing Jackson property names if you use naming strategies. Also make sure you recognize both "get*" and "is*" as attribute name patterns as Jackson infers default names using JavaBean convention.- Returns:
trueif force jackson property names. default ittrue, setfalseto disable
- Default:
true
-
forceJacksonIgnoreFields
boolean forceJacksonIgnoreFields- Returns:
- if put
JsonIgnoreon fields, defaults tofalse
- Default:
false
-
forceEqualsInWithers
boolean forceEqualsInWithersIfforceEqualsInWithersenabled, generated with-copy methods will have equality check forced.==for integer primitives,floatToIntBits ==for floating point, and.equals()for the reference values. Some usage patterns might require strict equality check during copy to function properly, while for other usages it's just an optimisation.- Returns:
- if equality check should be forced in withers, defaults to
false
- Default:
false
-
jacksonIntegration
boolean jacksonIntegrationSetting this tofalsewould disable any special jackson integration capabilities. While out-of-the-box Jackson readiness is a good things in the most cases, for some cases it might get in the way of highly customized Jackson infrastructure. When disabled, there are no any special stuff generated such asJsonPropertyannotations or internalJsondelegate class together withJsonCreatormethod. This allows to placeJsonSerialize/JsonDeserializeannotations on the value types without redundant support code being generated.- Returns:
trueif generate special Jackson code when encounteredJsonSerialize/JsonDeserialize. Default istrue.
- Default:
true
-
weakInterning
boolean weakInterningWhenweakInterningis enabled, then for value types with @Value.Immutable(intern=true)weak (seeWeakReference) interning will be used.- Returns:
trueif enable weak interning forintern=truevalues, defaults tofalse
- Default:
false
-
alwaysPublicInitializers
boolean alwaysPublicInitializersAll initializers (the methods to set attribute values on a builder) usually have public visibility regardless of the visibility of the attribute accessors. Usually this doesn't matter, especially for value types defined as interfaces (where all accessors public). But sometimes there's a need to have abstract class with finer-grained access control to attributes, which also require initializers to follow the access level of accessors defining attributes. Set this flag tofalseif initializers (builder setters) should follow access level of attributes. Note this flag is disregarded whenstagedBuilder()is enabled which generates stage interfaces which requires public access anyway.- Returns:
trueif force all initializers to public. Default is true
- Default:
true
-
builderVisibility
Value.Style.BuilderVisibility builderVisibilitySpecify the mode in which visibility of generated value type is derived from abstract value type. It is a good idea to not specify such attributes inline with immutable values, but rather create style annotation (@see Style).- Returns:
- implementation visibility
- Default:
PUBLIC
-
builderVisibilityString
String builderVisibilityStringSpecify the mode in which visibility of generated value type is derived from abstract value type. Specifying this will overridebuilderVisibility()and the reason why this option as a string exists, is to avoid javac warnings mentioned in #291.- Returns:
- implementation visibility as string
- Default:
""
-
throwForInvalidImmutableState
Class<? extends RuntimeException> throwForInvalidImmutableStateRuntime exception to throw when an immutable object is in an invalid state. I.e. when some mandatory attributes are missing and immutable object cannot be built. The runtime exception class must have a constructor that takes a single string, otherwise there will be compile error in the generated code.The default exception type is
IllegalStateException. In case if specified exception type have public constructor taking array of strings (can be varargs), then missing parameter names will be passed to that constructor. Otherwise, string constructor is always expected to be present to take formatted error message. It is always advisable have string constructor even in the presence of attribute names array constructor as some additional generators might use string constructor for reporting other invalid state issues.Technically we allow exception class to be checked (non-runtime), but not all processor features might be generated correctly (they may not expect). So use checked exception only if this work with your set of use-cases: there is no guarantee that it will be ever supported in all processor components/templates
- Returns:
- exception type
- Default:
java.lang.IllegalStateException.class
-
throwForNullPointer
Class<? extends RuntimeException> throwForNullPointerRuntime exception to throw when null reference is passed to non-nullable parameter or occured in array/container that must not contain nulls. It is expected that the exception will have public constructor receiving string as message/parameter name. The default isNullPointerExceptionand the calls are usually delegated toObjects.requireNonNull(Object)or similar utility throwingNullPointerException.- Returns:
- exception type
- Default:
java.lang.NullPointerException.class
-
depluralize
boolean depluralizeDepluralize names for collection and map attributes used for generating derived method names, such asadd()andput(). In order to enable depluralization usedepluralize = true: this will trim trailing "s" if present to create singular form ("*ies" to "*y" is also supported). Exceptions are provided usingdepluralizeDictionary()array of "singular:plural" pairs as alternative to mechanical "*s" depluralization.@Value.Style( depluralize = true, // enable feature depluralizeDictionary = {"person:people", "foot:feet"}) // specifying dictionary of exceptionsWhen given the dictionary defined as"person:people", "foot:feet"then depluralization examples for collectionadd*method in builder would be:- boats -> addBoat
- people -> addPerson
- feet -> addFoot
- feetPeople -> addFeetPerson
- peopleRepublics -> addPeopleRepublic
false: feature is disabled, compatible with previous versions.Instead
- Returns:
trueif depluralization enabled.- See Also:
- Default:
false
-
depluralizeDictionary
String[] depluralizeDictionaryDictionary of exceptions — array of "singular:plural" pairs as alternative to mechanical "*s" depluralization. Suppress trimming of trailing "s" for certain words by using exceptions of form"words:words"or simply"words". Important to note is that words will be converted to lowercase and identifier in question consists of couple of words joined using camel case — only a last segment will be considered for depluralization when matching dictionary. Uninterpretable pairs will be ignored. By default no dictionary is supplied and depluralization performed only by mechanical "*s" trimming.This attribute is semi-deprecated in favor of using
Value.Style.Depluralize.dictionary()annotation which may be placed on a package, type or as meta-annotation. And dictionary will be merged across all applicable definitions.- Returns:
- array of "singular:plural" pairs.
- See Also:
- Default:
{}
-
immutableCopyOfRoutines
Class<?>[] immutableCopyOfRoutinesYou can provide classes which must contain copyOf method with relevant overloads which should not have ambiguous cases as it will be fully a subject to JLS rules of static imports and compile time overload resolution.Tha major use case is custom validation and normalization of the attribute values by types. Validations specific to a value object or it's attributes could be performed using
Note: This attribute-style is experimental and may be changed in near releases. The manner in which routines are applied
- Returns:
- classes, for which static imports like
import static ..Type.immutableCopyOf;will be generated along with corresponding invocations ofimmutableCopyOfmethod when accepting parameters.
- Default:
{}
-
stagedBuilder
boolean stagedBuilderStaged (aka telescopic) builders are a special flavor of builders which provides compile-time safety to a staged building. Providing proposals to insert mandatory attributes one by one, and then allowing adding any optional or collection attributes in any order before calling the build method. This option also impliesstrictBuilder()is automatically enabled.Note: this functionality may not play well with other functionality, may be auto-disabled in certain configurations like implementations nested in builder.
- Returns:
- if telescopic builders are used,
falseby default
- Default:
false
-
builtinContainerAttributes
boolean builtinContainerAttributesSettingbuiltinContainerAttributestofalsewould disable generation of built-in convenience features of automatically recognized container types such asOptional,List,Map. This will turn all attribute types into nothing special setters(initializers) and getters. However any registered encodings (type customizers) will be still processed. One of the purposes of this style control is to provide clean-slate when only registered encodings will impact type generation, but none of the built-in types would be applied. Note: that this style controls recognition of the attribute types, but not kind of attributes such as those specified byValue.DefaultorNullableannotations.- Returns:
trueif builtin container attributes should be supported.trueis the default
- Default:
true
-
beanFriendlyModifiables
boolean beanFriendlyModifiablesIf enabled, modifiable type will have void setters and will look more like JavaBean. This is modifiable companion types only, not for builders and other types of generated artifacts.Note, we are not supporting JavaBean specification in any way except that Immutables can be used/configured to be partially compatible with some of the conventions.
- Returns:
truefor void setters and minor tweaks to make modifiables more bean-friendly.falseis the default
- Default:
false
-
allMandatoryParameters
boolean allMandatoryParametersIf enabled mandatory attributes would be auto-propagated to be parameters of value object constructor.This parameter conflicts with
allParameters()and is ignored whenallParametersis enabled- Returns:
trueto turn mandatory attributes into parameters.falseis the default
- Default:
false
-
transientDerivedFields
boolean transientDerivedFieldsWhentransientDerivedFieldsis enabled (as it by default), the backing fields for derived attributes will be marked astransient(unless type isSerializableby using regular Java serialization (not for when structural serialization is on via @Serial.Structural). When setfalse, the processor we will not add anytransientannotations to derived fields. This is only for derived fields. Any fields for lazy attributes are alwaystransientand ready to be reinitialized lazily after object is deserialized regardless of serialization/persistence technology.- Returns:
- default is
truefor backward compatibility. Set tofalseto disable
- Default:
true
-
finalInstanceFields
boolean finalInstanceFieldsDisable final fields only if there are no other way, considered unsafe. This is only about instance fields of Immutable implementation class, will not apply to a lot of their places/generators.- Returns:
- default is
true, do not switch off.
- Default:
true
-
redactedMask
String redactedMaskString to substitute value of the attribute in a generatedtoStringimplementation whenValue.Redactedannotation is applied to the attribute.By default it is an empty string, which also mean that the attribute will not appear in the
toStringoutput. If you set it to some value, then it will be printed.- Returns:
- redacted value substitution string
- Default:
""
-
nullableAnnotation
String nullableAnnotationImmutables recognizes nullable annotation by simple name. For most cases this is sufficient. But for some cases it's needed to customize this annotation simple name andnullableAnnotationcan be used to set custom simple name for nullable annotation. While we recommend against this change, this may be occasionally be needed. Except for simple name detection,javax.annotation.Nullableandjavax.annotation.CheckForNullare always recognized as nullable annotations.- Returns:
- nullable annotation simple name
- Default:
"Nullable"
-
attributeBuilderDetection
boolean attributeBuilderDetectionWhen enabled: immutable attributes with discoverable builders receive the additional builder API:For single children:
BuilderT *Builder()ParentT *Builder(BuilderT builder)
For a collection of children:
BuilderT add*Builder()ParentT addAll*Builder(Iterable<BuilderT> builderCollection)ParentT addAll*Builder(BuilderT... builderArgs)List<BuilderT> *Builders()In strict mode, you may only set the builder via
*Builder(BuilderT builder)once, but you may call*Builder()multiple times, in which the same builder is returned. If the nested immutable is also strict, then you will only be able to set properties on the child builder once.To discover builders on value attributes the value methods are scanned for method names matching a patterns specified in
attributeBuilder(). This style parameter is experimental and may change in future.- Returns:
- true to enable the feature.
- Default:
false
-
attributeBuilder
String[] attributeBuilderPattern for detecting builders.attributeBuilder()applies to both static and instance methods. In the case a builder is only discoverable through a value instance method, the builder class must have a public no-arg static construction method. To use a no-arg public constructor, a special token "new" should be specified. example: new token required to find this builder.class MyObject { class Builder { public Builder() {...} public Builder(MyObject copy) {...} MyObject build() {...} } }This is detection pattern, not formatting pattern. It defines how to recognize a nested builder. Only applies ifattributeBuilderDetection()istrue.- Returns:
- naming template
- Default:
{"Builder", "*Builder", "builder", "from", "build", "*Build", "new"}
-
getBuilder
String getBuilderNaming template for retrieving a nested builder. Only applies ifattributeBuilderDetection()istrue.- Returns:
- naming template.
- Default:
"*Builder"
-
setBuilder
String setBuilderNaming template for setting a nested builder. This may be called only once in strict mode. Only applies ifattributeBuilderDetection()istrue.- Returns:
- naming template.
- Default:
"*Builder"
-
addBuilder
String addBuilderNaming template for adding a new builder instance to a collection. Only applies ifattributeBuilderDetection()istrue.- Returns:
- naming template.
- Default:
"add*Builder"
-
addAllBuilder
String addAllBuilderNaming template for adding a collection of builders. Only applies ifattributeBuilderDetection()istrue.- Returns:
- naming template.
- Default:
"addAll*Builders"
-
getBuilders
String getBuildersNaming template for retrieving an immutable list of builders. Only applies ifattributeBuilderDetection()istrue.- Returns:
- naming template.
- Default:
"*Builders"
-
allowedClasspathAnnotations
Class<? extends Annotation>[] allowedClasspathAnnotationsImmutables applies some annotations if found on classpath. These include:- @
org.immutables.value.Generated - @
javax.annotation.Generated - @
java.annotation.processing.Generated - @
javax.annotation.concurrent.Immutable - @
javax.annotation.ParametersAreNonnullByDefault - @
javax.annotation.CheckReturnValue - @
edu.umd.cs.findbugs.annotations.SuppressFBWarnings - @
com.google.errorprone.annotations.Var - @
com.google.errorprone.annotations.Immutable - ... and others, etc
In order to simply disable all such annotation auto-discovery, you can put some dummy annotation like
java.lang.Override, as in:Style(allowedClasspathAnnotations = {java.lang.Override.class})The array will no longer be empty as by default so only specified entries will be applied. Please note that standardjava.langannotations likeOverride,Deprecated,SuppressWarningswill always be applied where supported, so this configuration have no effect on those. At the same time,javax.annotation.*orjava.annotation.processing.*are configurable by this style attribute. Another exception is when some annotation is put on abstract value type or attribute and then propagated to corresponding/related elements of generated classes, these other mechanisms do not count as complementary annotation generation regulated by this property.Another way to inhibit some classpath entries from discovery is using class-path fence using META-INF extension mechanism. That mechanism is a general classpath discovery blacklist and overrides any whitelist allowed here. Add unwanted fully qualified class name prefixes (for example, like full class names, or package names ending with a dot) as the lines to the
META-INF/extensions/org.immutables.inhibit-classpathresource file available in classpath.- Returns:
- a non-empty array of only allowed auto-discovered annotations. Empty by default, which allows any auto-discovered annotation support for backward compatibility.
- Default:
{}
- @
-
fallbackNullableAnnotation
Class<? extends Annotation> fallbackNullableAnnotationFor many cases of nullable annotation is just copied to generated code when recognized (by simple name, seenullableAnnotation()). But for some cases we need to internally insert some nullable annotation when we don't know any "original" annotation. By default, we assume that would bejavax.annotation.Nullable(if it present on the classpath during compilation). When you setfallbackNullableAnnotation()to non-default value (default value isjava.lang.annotation.Inheritedwhich serves as a placeholder for an unspecified value) value, we would use that annotation in such cases.Note that this annotation would always be on the compilation classpath (as it is specified as class literal in a style annotation, but will not be otherwise validated as applicable and will be used verbatim in all places where we ought to insert nullable annotation without the link to any "original" nullable annotation in the hand-written code.
- Returns:
- fallback nullable annotation to use. Default values is unspecified encoded as
Inherited.classso thatjavax.annotation.Nullableannotation will be used if found on classpath.
- Default:
java.lang.annotation.Inherited.class
-
limitStringLengthInToString
int limitStringLengthInToStringSetting to trim strings longer than a defined length when calling the toString method.- Returns:
- string limit, by default
0i.e. no limit
- Default:
0
-
jakarta
boolean jakartaIf enabled,jakarta.*packages will take over any relevantjavax.*. This includes primarilyjakarta.annotation.*andjakarta.validation.*.Note that classpath inhibitor or
allowedClasspathAnnotations()will still take effect, it's just so that- Returns:
trueif enabled. The default isfalse.
- Default:
false
-