Annotation Type Value.Style
-
@Target({TYPE,PACKAGE,ANNOTATION_TYPE}) public static @interface Value.StyleNaming and structural style could be used to customize convention of the generated immutable implementations and companion classes. It could be placed on a class or package directly or serve as meta annotation. When used as meta-annotation, then annotation could be placed on a class, surrounding top level class or even a package (declared inpackage-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-annotationBe 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.
-
-
Optional Element Summary
Optional Elements Modifier and Type Optional Element Description java.lang.StringaddAdd value to collection attribute from iterablejava.lang.StringaddAllAdd all values to collection attribute from iterablejava.lang.StringaddAllBuilderNaming template for adding a collection of builders.java.lang.StringaddBuilderNaming template for adding a new builder instance to a collection.java.lang.Class<? extends java.lang.annotation.Annotation>[]additionalJsonAnnotationsList of additional annotations to pass through for any jackson json object.booleanallMandatoryParametersIf enabled mandatory attributes would be auto-propagated to be parameters of value object constructor.java.lang.Class<? extends java.lang.annotation.Annotation>[]allowedClasspathAnnotationsImmutables applies some annotations if found on classpath.booleanallParametersWhentrue— all settable attributes are considered as they are annotated withValue.Parameter.booleanalwaysPublicInitializersAll initializers (the methods to set attribute values on a builder) usually have public visibility regardless of the visibility of the attribute accessors.java.lang.String[]attributeBuilderPattern for detecting builders.booleanattributeBuilderDetectionWhen enabled: immutable attributes with discoverable builders receive the additional builder API:booleanattributelessSingletonEnablingattributelessSingletonswitches to old behavior of 2.0.x version when immutable instances which had no attributes defined we automatically generated as singleton havinginstance()accessor.booleanbeanFriendlyModifiablesIf enabled, modifiable type will have void setters and will look more like JavaBean.java.lang.StringbuildInstance creation method on builder.java.lang.StringbuilderBuilder creator method.Value.Style.BuilderVisibilitybuilderVisibilitySpecify the mode in which visibility of generated value type is derived from abstract value type.java.lang.StringbuilderVisibilityStringSpecify the mode in which visibility of generated value type is derived from abstract value type.java.lang.StringbuildOrThrowNaming template for thebuildOrThrowmethod which accept exception factory function for throwing in case not all mandatory properties are set.booleanbuiltinContainerAttributesSettingbuiltinContainerAttributestofalsewould disable generation of built-in convenience features of automatically recognized container types such asOptional,List,Map.java.lang.StringcanBuildNaming template for thecanBuildmethod on a builder that return boolean if it can "safely" build an object, i.e.java.lang.StringclearClear all collection attributes and unset(or other container).booleanclearBuilderWhen enabled:clearmethod will be generated on builder to reset state of a builder.java.lang.StringcopyOfCopy constructor method name.java.lang.StringcreateFactory method for modifiable implementation, could be "new" to create objects using constructor.booleandeepImmutablesDetectionDeep analysis of immutable types enables additional convenience features.booleandefaultAsDefaultThis funny-named named attribute, when enabled makes default accessor methods defined in interfaces/traits behave as if they annotated as @Value.Default.Value.ImmutabledefaultsSpecify default options for the generated immutable objects.booleandeferCollectionAllocationWhen this optimisation in enabled then the processor tries to defer allocation of collection in builder and modifiable objects.java.lang.StringdelegateToStringDelegatestoStringimplementation completely to a fully qualified path to a method name, exampledelegateToString="com.whatever.packg.ToStringer.stringify".booleandepluralizejava.lang.String[]depluralizeDictionaryDictionary of exceptions — array of "singular:plural" pairs as alternative to mechanical "*s" depluralization.java.lang.Class<? extends java.lang.annotation.Annotation>fallbackNullableAnnotationFor many cases of nullable annotation is just copied to generated code when recognized (by simple name, seenullableAnnotation()).booleanfinalInstanceFieldsDisable final fields only if there are no other way, considered unsafe.booleanforceEqualsInWithersIfforceEqualsInWithersenabled, generated with-copy methods will have equality check forced.booleanforceJacksonIgnoreFieldsbooleanforceJacksonPropertyNamesAs there are some ambiguities with how certain field prefixes work ("get", "is") we by default force whatever is inferred by Immutables.java.lang.StringfromMethod to initialize builder with values from instance.booleangenerateSuppressAllWarningsGenerateSuppressWarnings("all")in generated code.java.lang.String[]getPatterns to recognize accessors.java.lang.StringgetBuilderNaming template for retrieving a nested builder.java.lang.StringgetBuildersNaming template for retrieving an immutable list of builders.booleanheaderCommentsEnable if you needed to copy header comments from an originating source file with abstract types to generated (derived) implementation classes.java.lang.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.booleanimplementationNestedInBuilderBy default builder is generated as inner builder class nested in immutable value class.java.lang.StringincludeHashCodeIfincludeHashCodeis not empty it will be used as part of generated `hashCode`.java.lang.StringinitBuilder initialization method.java.lang.StringinstanceSingleton accessor method namejava.lang.StringisInitializedMethod to determine if all required attributes are set.java.lang.StringisSetMethod to determine if attribute is setbooleanjacksonIntegrationSetting this tofalsewould disable any special jackson integration capabilities.booleanjakartaIf enabled,jakarta.*packages will take over any relevantjavax.*.booleanjdk9CollectionsWhentrue— will use JDK 9+ immutable collections to implementList/Set/Mapattributes.booleanjdkOnlyWhentrue— forces to generate code which use only JDK 7+ standard library classes.intlimitStringLengthInToStringSetting to trim strings longer than a defined length when calling the toString method.java.lang.StringnewBuilderBuilder 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.java.lang.StringnullableAnnotationImmutables recognizes nullable annotation by simple name.java.lang.StringofConstructor method name.booleanoptionalAcceptNullableSpecify whether init, copy and factory methods and constructors for an unwrappedXofOptional<X>should acceptnullvalues as empty value.booleanovershadowImplementationMakes abstract value type predominantly used in generated signatures rather than immutable implementation class.java.lang.StringpackageGeneratedNaming templatepackageGeneratedused to derive name of the package where the annotation processor should put generated classes for corresponding immutable values.java.lang.Class<? extends java.lang.annotation.Annotation>[]passAnnotationsList type of annotations to copy over from abstract value type to immutable implementation class.booleanprivateNoargConstructorGenerate a private no-argument constructor in generated code.booleanprotectedNoargConstructorGenerate a protected no-argument constructor, mainly for reflective usage by advanced toolkits.java.lang.StringputPuts entry to a map attributejava.lang.StringputAllPuts all entries to a map attributejava.lang.StringredactedMaskString to substitute value of the attribute in a generatedtoStringimplementation whenValue.Redactedannotation is applied to the attribute.java.lang.StringsetModifiable object "setter" method.java.lang.StringsetBuilderNaming template for setting a nested builder.booleanstagedBuilderStaged (aka telescopic) builders are a special flavor of builders which provides compile-time safety to a staged building.booleanstrictBuilderWhentrue— forces to generate strict builder code.booleanstrictModifiableStrict modifiable will refuse any accessor value (by throwingIllegalStateException) which is mandatory.java.lang.Class<? extends java.lang.RuntimeException>throwForInvalidImmutableStateRuntime exception to throw when an immutable object is in an invalid state.java.lang.Class<? extends java.lang.RuntimeException>throwForNullPointerRuntime exception to throw when null reference is passed to non-nullable parameter or occured in array/container that must not contain nulls.java.lang.StringtoBuilderNaming template for thetoBuildermethod on a immutable instance that returns new builder on which merge method is already called on this instancebuilder.from(this).java.lang.StringtoImmutableMethod to convert to instance of modifiable type to "canonical" immutable instance.booleantransientDerivedFieldsWhentransientDerivedFieldsis 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).java.lang.String[]typeAbstractNaming templates to detect base/raw type name from provided abstract value type name.java.lang.StringtypeBuilderGenerated builder class name.java.lang.StringtypeImmutableName template to generate immutable implementation type by using base/raw type name.java.lang.StringtypeImmutableEnclosingUmbrella nesting class name generated usingValue.Enclosing.java.lang.StringtypeImmutableNestedImmutable class name when generated under umbrella class usingValue.Enclosingannotation.java.lang.StringtypeInnerBuilderInner builder class name which will be matched to be extend/super for generated builder.java.lang.StringtypeInnerModifiableInner builder class name which will be matched to be extend/super for generated Modifiable class.java.lang.StringtypeModifiableModifiable companion class name templatejava.lang.StringtypeWithGenerated "with" interface name.java.lang.StringunderrideEqualsjava.lang.StringunderrideHashCodeDetects and use method named as specified to customize generatedhashCode.java.lang.StringunderrideToStringbooleanunsafeDefaultAndDerivedAs of 2.1 we are switching to safe generation of derived and default values when there are more than one such attribute.java.lang.StringunsetUnset attribute method.Value.Style.ValidationMethodvalidationMethodWhentrue— disables check that all required attributes have been provided to a builder.Value.Style.ImplementationVisibilityvisibilitySpecify the mode in which visibility of generated value type is derived from abstract value type.java.lang.StringvisibilityStringSpecify the mode in which visibility of generated value type is derived from abstract value type.booleanweakInterningWhenweakInterningis enabled, then for value types with @Value.Immutable(intern=true)weak (seeWeakReference) interning will be used.java.lang.StringwithModify-by-copy "with" method.java.lang.StringwithUnaryOperatorModify-by-copy method which receivesUnaryOperatorto transform an attribute before constructing a copy of immutable object.
-
-
-
Element Detail
-
get
java.lang.String[] get
Patterns 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
java.lang.String init
Builder initialization method. i.e. "setter" in builder. Do not confuse withset()- Returns:
- naming template
- Default:
- "*"
-
-
-
withUnaryOperator
java.lang.String withUnaryOperator
Modify-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:
- ""
-
-
-
of
java.lang.String of
Constructor 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"
-
-
-
builder
java.lang.String builder
Builder 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:
newBuilder(),build()
- Default:
- "builder"
-
-
-
newBuilder
java.lang.String newBuilder
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. 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:
build()
- Default:
- "new"
-
-
-
buildOrThrow
java.lang.String buildOrThrow
Naming 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
java.lang.String canBuild
Naming 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
java.lang.String toBuilder
Naming 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
java.lang.String underrideHashCode
Detects 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:
- ""
-
-
-
delegateToString
java.lang.String delegateToString
DelegatestoStringimplementation 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
java.lang.String includeHashCode
IfincludeHashCodeis 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:
- ""
-
-
-
set
java.lang.String set
Modifiable object "setter" method. Used for mutable implementations. Do not confuse withinit()- Returns:
- naming template
- Default:
- "set*"
-
-
-
typeAbstract
java.lang.String[] typeAbstract
Naming 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
java.lang.String typeImmutable
Name 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
java.lang.String typeImmutableEnclosing
Umbrella nesting class name generated usingValue.Enclosing.- Returns:
- naming template
- Default:
- "Immutable*"
-
-
-
typeImmutableNested
java.lang.String typeImmutableNested
Immutable class name when generated under umbrella class usingValue.Enclosingannotation.- Returns:
- naming template
- See Also:
typeImmutable(),typeImmutableEnclosing()
- Default:
- "*"
-
-
-
packageGenerated
java.lang.String packageGenerated
Naming 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 defaults
Specify 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 jdkOnly
Whentrue— 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 jdk9Collections
Whentrue— 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 strictBuilder
Whentrue— 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 strictModifiable
Strict 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 validationMethod
Whentrue— disables check that all required attributes have been provided to a builder.- Default:
- org.immutables.value.Value.Style.ValidationMethod.SIMPLE
-
-
-
allParameters
boolean allParameters
When
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 defaultAsDefault
This 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 headerComments
Enable 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
java.lang.Class<? extends java.lang.annotation.Annotation>[] passAnnotations
List 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
java.lang.Class<? extends java.lang.annotation.Annotation>[] additionalJsonAnnotations
List 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 visibility
Specify 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:
- org.immutables.value.Value.Style.ImplementationVisibility.SAME
-
-
-
visibilityString
java.lang.String visibilityString
Specify 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 optionalAcceptNullable
Specify 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 generateSuppressAllWarnings
GenerateSuppressWarnings("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 privateNoargConstructor
Generate 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 protectedNoargConstructor
Generate 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 attributelessSingleton
EnablingattributelessSingletonswitches 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 unsafeDefaultAndDerived
As 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 clearBuilder
When 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:
clear()
- Default:
- false
-
-
-
deferCollectionAllocation
boolean deferCollectionAllocation
When 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 deepImmutablesDetection
Deep 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 overshadowImplementation
Makes 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 implementationNestedInBuilder
By 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 forceJacksonPropertyNames
As 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
-
-
-
forceEqualsInWithers
boolean forceEqualsInWithers
IfforceEqualsInWithersenabled, 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 jacksonIntegration
Setting 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
-
-
-
alwaysPublicInitializers
boolean alwaysPublicInitializers
All 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 builderVisibility
Specify 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:
- org.immutables.value.Value.Style.BuilderVisibility.PUBLIC
-
-
-
builderVisibilityString
java.lang.String builderVisibilityString
Specify 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
java.lang.Class<? extends java.lang.RuntimeException> throwForInvalidImmutableState
Runtime 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
java.lang.Class<? extends java.lang.RuntimeException> throwForNullPointer
Runtime 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 depluralize
Depluralize 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:
Value.Style.Depluralize
- Default:
- false
-
-
-
depluralizeDictionary
java.lang.String[] depluralizeDictionary
Dictionary 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:
depluralize(),Value.Style.Depluralize.dictionary()
- Default:
- {}
-
-
-
immutableCopyOfRoutines
java.lang.Class<?>[] immutableCopyOfRoutines
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.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 stagedBuilder
Staged (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 builtinContainerAttributes
SettingbuiltinContainerAttributestofalsewould 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 beanFriendlyModifiables
If 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 allMandatoryParameters
If 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 transientDerivedFields
WhentransientDerivedFieldsis 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 finalInstanceFields
Disable 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
java.lang.String redactedMask
String 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
java.lang.String nullableAnnotation
Immutables 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 attributeBuilderDetection
When 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
java.lang.String[] attributeBuilder
Pattern 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
java.lang.String getBuilder
Naming template for retrieving a nested builder. Only applies ifattributeBuilderDetection()istrue.- Returns:
- naming template.
- Default:
- "*Builder"
-
-
-
setBuilder
java.lang.String setBuilder
Naming 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
java.lang.String addBuilder
Naming template for adding a new builder instance to a collection. Only applies ifattributeBuilderDetection()istrue.- Returns:
- naming template.
- Default:
- "add*Builder"
-
-
-
addAllBuilder
java.lang.String addAllBuilder
Naming template for adding a collection of builders. Only applies ifattributeBuilderDetection()istrue.- Returns:
- naming template.
- Default:
- "addAll*Builders"
-
-
-
getBuilders
java.lang.String getBuilders
Naming template for retrieving an immutable list of builders. Only applies ifattributeBuilderDetection()istrue.- Returns:
- naming template.
- Default:
- "*Builders"
-
-
-
allowedClasspathAnnotations
java.lang.Class<? extends java.lang.annotation.Annotation>[] allowedClasspathAnnotations
Immutables 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
java.lang.Class<? extends java.lang.annotation.Annotation> fallbackNullableAnnotation
For 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
-
-
-
jakarta
boolean jakarta
If 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
-
-