lombok的坑
java -jar lombok.jar config -g --verbose
配置系统 --- Configuration system (projectlombok.org)
##
## Key : checkerframework
## Type: checkerframework-version
##
## If set with the version of checkerframework.org (in major.minor, or just 'true' for the latest supported version), create relevant checkerframework.org annotations for code lombok generates (default: false).
##
## Examples:
#
# clear checkerframework
# checkerframework = major.minor (example: 3.2 - and no higher than 4.0) or true or false
#
##
## Key : config.stopBubbling
## Type: boolean
##
## Tell the configuration system it should stop looking for other configuration files (default: false).
##
## Examples:
#
# clear config.stopBubbling
# config.stopBubbling = [false | true]
#
##
## Key : lombok.accessors.chain
## Type: boolean
##
## Generate setters that return 'this' instead of 'void' (default: false).
##
## Examples:
#
# clear lombok.accessors.chain
# lombok.accessors.chain = [false | true]
#
##
## Key : lombok.accessors.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Accessors is used.
##
## Examples:
#
# clear lombok.accessors.flagUsage
# lombok.accessors.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.accessors.fluent
## Type: boolean
##
## Generate getters and setters using only the field name (no get/set prefix) (default: false).
##
## Examples:
#
# clear lombok.accessors.fluent
# lombok.accessors.fluent = [false | true]
#
##
## Key : lombok.accessors.prefix
## Type: list of string
##
## Strip this field prefix, like 'f' or 'm_', from the names of generated getters and setters.
##
## Examples:
#
# clear lombok.accessors.prefix
# lombok.accessors.prefix += <text>
# lombok.accessors.prefix -= <text>
#
##
## Key : lombok.addGeneratedAnnotation
## Type: boolean
##
## Generate @javax.annotation.Generated on all generated code (default: false). Deprecated, use 'lombok.addJavaxGeneratedAnnotation' instead.
##
## Examples:
#
# clear lombok.addGeneratedAnnotation
# lombok.addGeneratedAnnotation = [false | true]
#
##
## Key : lombok.addJavaxGeneratedAnnotation
## Type: boolean
##
## Generate @javax.annotation.Generated on all generated code (default: follow lombok.addGeneratedAnnotation).
##
## Examples:
#
# clear lombok.addJavaxGeneratedAnnotation
# lombok.addJavaxGeneratedAnnotation = [false | true]
#
##
## Key : lombok.addLombokGeneratedAnnotation
## Type: boolean
##
## Generate @lombok.Generated on all generated code (default: false).
##
## Examples:
#
# clear lombok.addLombokGeneratedAnnotation
# lombok.addLombokGeneratedAnnotation = [false | true]
#
##
## Key : lombok.addNullAnnotations
## Type: nullity-annotation-library
##
## Generate some style of null annotation for generated code where this is relevant. (default: none).
##
## Examples:
#
# clear lombok.addNullAnnotations
# lombok.addNullAnnotations = none | javax | eclipse | jetbrains | netbeans | androidx | android.support | checkerframework | findbugs | spring | jml | CUSTOM:com.foo.my.nonnull.annotation:com.foo.my.nullable.annotation
#
##
## Key : lombok.addSuppressWarnings
## Type: boolean
##
## Generate @java.lang.SuppressWarnings("all") on all generated code (default: true).
##
## Examples:
#
# clear lombok.addSuppressWarnings
# lombok.addSuppressWarnings = [false | true]
#
##
## Key : lombok.allArgsConstructor.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @AllArgsConstructor is used.
##
## Examples:
#
# clear lombok.allArgsConstructor.flagUsage
# lombok.allArgsConstructor.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.anyConstructor.addConstructorProperties
## Type: boolean
##
## Generate @ConstructorProperties for generated constructors (default: false).
##
## Examples:
#
# clear lombok.anyConstructor.addConstructorProperties
# lombok.anyConstructor.addConstructorProperties = [false | true]
#
##
## Key : lombok.anyConstructor.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if any of the XxxArgsConstructor annotations are used.
##
## Examples:
#
# clear lombok.anyConstructor.flagUsage
# lombok.anyConstructor.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.anyConstructor.suppressConstructorProperties
## Type: boolean
##
## Suppress the generation of @ConstructorProperties for generated constructors (default: false).
##
## Examples:
#
# clear lombok.anyConstructor.suppressConstructorProperties
# lombok.anyConstructor.suppressConstructorProperties = [false | true]
#
##
## Key : lombok.builder.className
## Type: string
##
## Default name of the generated builder class. A * is replaced with the name of the relevant type (default = *Builder).
##
## Examples:
#
# clear lombok.builder.className
# lombok.builder.className = <text>
#
##
## Key : lombok.builder.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Builder is used.
##
## Examples:
#
# clear lombok.builder.flagUsage
# lombok.builder.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.cleanup.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Cleanup is used.
##
## Examples:
#
# clear lombok.cleanup.flagUsage
# lombok.cleanup.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.copyableAnnotations
## Type: list of type-name
##
## Copy these annotations to getters, setters, with methods, builder-setters, etc.
##
## Examples:
#
# clear lombok.copyableAnnotations
# lombok.copyableAnnotations += <fully.qualified.Type>
# lombok.copyableAnnotations -= <fully.qualified.Type>
#
##
## Key : lombok.data.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Data is used.
##
## Examples:
#
# clear lombok.data.flagUsage
# lombok.data.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.delegate.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Delegate is used.
##
## Examples:
#
# clear lombok.delegate.flagUsage
# lombok.delegate.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.equalsAndHashCode.callSuper
## Type: enum (lombok.core.configuration.CallSuperType)
##
## When generating equals and hashCode for classes that extend something (other than Object), either automatically take into account superclass implementation (call), or don't (skip), or warn and don't (warn). (default = warn).
##
## Examples:
#
# clear lombok.equalsAndHashCode.callSuper
# lombok.equalsAndHashCode.callSuper = [CALL | SKIP | WARN]
#
##
## Key : lombok.equalsAndHashCode.doNotUseGetters
## Type: boolean
##
## Don't call the getters but use the fields directly in the generated equals and hashCode method (default = false).
##
## Examples:
#
# clear lombok.equalsAndHashCode.doNotUseGetters
# lombok.equalsAndHashCode.doNotUseGetters = [false | true]
#
##
## Key : lombok.equalsAndHashCode.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @EqualsAndHashCode is used.
##
## Examples:
#
# clear lombok.equalsAndHashCode.flagUsage
# lombok.equalsAndHashCode.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.experimental.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if an experimental feature is used.
##
## Examples:
#
# clear lombok.experimental.flagUsage
# lombok.experimental.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.extensionMethod.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @ExtensionMethod is used.
##
## Examples:
#
# clear lombok.extensionMethod.flagUsage
# lombok.extensionMethod.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.extern.findbugs.addSuppressFBWarnings
## Type: boolean
##
## Generate @edu.umd.cs.findbugs.annotations.SuppressFBWarnings on all generated code (default: false).
##
## Examples:
#
# clear lombok.extern.findbugs.addSuppressFBWarnings
# lombok.extern.findbugs.addSuppressFBWarnings = [false | true]
#
##
## Key : lombok.fieldDefaults.defaultFinal
## Type: boolean
##
## If true, fields, in any file (lombok annotated or not) are marked as final. Use @NonFinal to override this.
##
## Examples:
#
# clear lombok.fieldDefaults.defaultFinal
# lombok.fieldDefaults.defaultFinal = [false | true]
#
##
## Key : lombok.fieldDefaults.defaultPrivate
## Type: boolean
##
## If true, fields without any access modifier, in any file (lombok annotated or not) are marked as private. Use @PackagePrivate or an explicit modifier to override this.
##
## Examples:
#
# clear lombok.fieldDefaults.defaultPrivate
# lombok.fieldDefaults.defaultPrivate = [false | true]
#
##
## Key : lombok.fieldDefaults.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @FieldDefaults is used.
##
## Examples:
#
# clear lombok.fieldDefaults.flagUsage
# lombok.fieldDefaults.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.fieldNameConstants.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @FieldNameConstants is used.
##
## Examples:
#
# clear lombok.fieldNameConstants.flagUsage
# lombok.fieldNameConstants.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.fieldNameConstants.innerTypeName
## Type: identifier-name
##
## The default name of the inner type generated by @FieldNameConstants. (default: 'Fields').
##
## Examples:
#
# clear lombok.fieldNameConstants.innerTypeName
# lombok.fieldNameConstants.innerTypeName = <javaIdentifier>
#
##
## Key : lombok.fieldNameConstants.uppercase
## Type: boolean
##
## The default name of the constants inside the inner type generated by @FieldNameConstants follow the variable name precisely. If this config key is true, lombok will uppercase them as best it can. (default: false).
##
## Examples:
#
# clear lombok.fieldNameConstants.uppercase
# lombok.fieldNameConstants.uppercase = [false | true]
#
##
## Key : lombok.getter.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Getter is used.
##
## Examples:
#
# clear lombok.getter.flagUsage
# lombok.getter.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.getter.lazy.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Getter(lazy=true) is used.
##
## Examples:
#
# clear lombok.getter.lazy.flagUsage
# lombok.getter.lazy.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.getter.noIsPrefix
## Type: boolean
##
## If true, generate and use getFieldName() for boolean getters instead of isFieldName().
##
## Examples:
#
# clear lombok.getter.noIsPrefix
# lombok.getter.noIsPrefix = [false | true]
#
##
## Key : lombok.helper.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Helper is used.
##
## Examples:
#
# clear lombok.helper.flagUsage
# lombok.helper.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.jacksonized.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Jacksonized is used.
##
## Examples:
#
# clear lombok.jacksonized.flagUsage
# lombok.jacksonized.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.log.apacheCommons.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @CommonsLog is used.
##
## Examples:
#
# clear lombok.log.apacheCommons.flagUsage
# lombok.log.apacheCommons.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.log.custom.declaration
## Type: custom-log-declaration
##
## Define the generated custom logger field.
##
## Examples:
#
# clear lombok.log.custom.declaration
# lombok.log.custom.declaration = my.cool.Logger my.cool.LoggerFactory.createLogger()(TOPIC,TYPE)
#
##
## Key : lombok.log.custom.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @CustomLog is used.
##
## Examples:
#
# clear lombok.log.custom.flagUsage
# lombok.log.custom.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.log.fieldIsStatic
## Type: boolean
##
## Make the generated logger fields static (default: true).
##
## Examples:
#
# clear lombok.log.fieldIsStatic
# lombok.log.fieldIsStatic = [false | true]
#
##
## Key : lombok.log.fieldName
## Type: identifier-name
##
## Use this name for the generated logger fields (default: 'log').
##
## Examples:
#
# clear lombok.log.fieldName
# lombok.log.fieldName = <javaIdentifier>
#
##
## Key : lombok.log.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if any of the log annotations is used.
##
## Examples:
#
# clear lombok.log.flagUsage
# lombok.log.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.log.flogger.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Flogger is used.
##
## Examples:
#
# clear lombok.log.flogger.flagUsage
# lombok.log.flogger.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.log.javaUtilLogging.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Log is used.
##
## Examples:
#
# clear lombok.log.javaUtilLogging.flagUsage
# lombok.log.javaUtilLogging.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.log.jbosslog.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @JBossLog is used.
##
## Examples:
#
# clear lombok.log.jbosslog.flagUsage
# lombok.log.jbosslog.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.log.log4j.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Log4j is used.
##
## Examples:
#
# clear lombok.log.log4j.flagUsage
# lombok.log.log4j.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.log.log4j2.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Log4j2 is used.
##
## Examples:
#
# clear lombok.log.log4j2.flagUsage
# lombok.log.log4j2.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.log.slf4j.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Slf4j is used.
##
## Examples:
#
# clear lombok.log.slf4j.flagUsage
# lombok.log.slf4j.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.log.xslf4j.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @XSlf4j is used.
##
## Examples:
#
# clear lombok.log.xslf4j.flagUsage
# lombok.log.xslf4j.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.noArgsConstructor.extraPrivate
## Type: boolean
##
## Generate a private no-args constructor for @Data and @Value (default: false).
##
## Examples:
#
# clear lombok.noArgsConstructor.extraPrivate
# lombok.noArgsConstructor.extraPrivate = [false | true]
#
##
## Key : lombok.noArgsConstructor.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @NoArgsConstructor is used.
##
## Examples:
#
# clear lombok.noArgsConstructor.flagUsage
# lombok.noArgsConstructor.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.nonNull.exceptionType
## Type: enum (lombok.core.configuration.NullCheckExceptionType)
##
## The type of the exception to throw if a passed-in argument is null (Default: NullPointerException).
##
## Examples:
#
# clear lombok.nonNull.exceptionType
# lombok.nonNull.exceptionType = [NullPointerException | IllegalArgumentException | Assertion | JDK | Guava]
#
##
## Key : lombok.nonNull.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @NonNull is used.
##
## Examples:
#
# clear lombok.nonNull.flagUsage
# lombok.nonNull.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.onX.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if onX is used.
##
## Examples:
#
# clear lombok.onX.flagUsage
# lombok.onX.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.requiredArgsConstructor.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @RequiredArgsConstructor is used.
##
## Examples:
#
# clear lombok.requiredArgsConstructor.flagUsage
# lombok.requiredArgsConstructor.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.setter.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Setter is used.
##
## Examples:
#
# clear lombok.setter.flagUsage
# lombok.setter.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.singular.auto
## Type: boolean
##
## If true (default): Automatically singularize the assumed-to-be-plural name of your variable/parameter when using @Singular.
##
## Examples:
#
# clear lombok.singular.auto
# lombok.singular.auto = [false | true]
#
##
## Key : lombok.singular.useGuava
## Type: boolean
##
## Generate backing immutable implementations for @Singular on java.util.* types by using guava's ImmutableList, etc. Normally java.util's mutable types are used and wrapped to make them immutable.
##
## Examples:
#
# clear lombok.singular.useGuava
# lombok.singular.useGuava = [false | true]
#
##
## Key : lombok.sneakyThrows.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @SneakyThrows is used.
##
## Examples:
#
# clear lombok.sneakyThrows.flagUsage
# lombok.sneakyThrows.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.standardException.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @StandardException is used.
##
## Examples:
#
# clear lombok.standardException.flagUsage
# lombok.standardException.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.superBuilder.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @SuperBuilder is used.
##
## Examples:
#
# clear lombok.superBuilder.flagUsage
# lombok.superBuilder.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.synchronized.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Synchronized is used.
##
## Examples:
#
# clear lombok.synchronized.flagUsage
# lombok.synchronized.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.toString.callSuper
## Type: enum (lombok.core.configuration.CallSuperType)
##
## When generating toString for classes that extend something (other than Object), either automatically take into account superclass implementation (call), or don't (skip), or warn and don't (warn). (default = skip).
##
## Examples:
#
# clear lombok.toString.callSuper
# lombok.toString.callSuper = [CALL | SKIP | WARN]
#
##
## Key : lombok.toString.doNotUseGetters
## Type: boolean
##
## Don't call the getters but use the fields directly in the generated toString method (default = false).
##
## Examples:
#
# clear lombok.toString.doNotUseGetters
# lombok.toString.doNotUseGetters = [false | true]
#
##
## Key : lombok.toString.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @ToString is used.
##
## Examples:
#
# clear lombok.toString.flagUsage
# lombok.toString.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.toString.includeFieldNames
## Type: boolean
##
## Include the field names in the generated toString method (default = true).
##
## Examples:
#
# clear lombok.toString.includeFieldNames
# lombok.toString.includeFieldNames = [false | true]
#
##
## Key : lombok.utilityClass.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @UtilityClass is used.
##
## Examples:
#
# clear lombok.utilityClass.flagUsage
# lombok.utilityClass.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.val.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if 'val' is used.
##
## Examples:
#
# clear lombok.val.flagUsage
# lombok.val.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.value.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @Value is used.
##
## Examples:
#
# clear lombok.value.flagUsage
# lombok.value.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.var.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if 'var' is used.
##
## Examples:
#
# clear lombok.var.flagUsage
# lombok.var.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.with.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @With is used.
##
## Examples:
#
# clear lombok.with.flagUsage
# lombok.with.flagUsage = [WARNING | ERROR | ALLOW]
#
##
## Key : lombok.withBy.flagUsage
## Type: enum (lombok.core.configuration.FlagUsageType)
##
## Emit a warning or error if @WithBy is used.
##
## Examples:
#
# clear lombok.withBy.flagUsage
# lombok.withBy.flagUsage = [WARNING | ERROR | ALLOW]
#
可以通过配置文件lombok.config来定制lombok:一次性配置lombok的属性可以服务整个项目或者工作台。需要注意该配置文件在lombok1.14+方可使用
根据官网的描述:lombok.config配置文件可以放在任何目录,作用于该目录和其子目录
针对实际项目建议放在工程的根目录或者src目录下(只是建议,你可以拒绝^_^)
配置系统对于在整个项目中配置常量(在项目中保持不变),比如日志变量的名称。配置系统还可以用来控制lombok将任何不喜欢的lombok特性的用法标记为警告,甚至是错误。
使用自定义lombok.config
lombok.config中配置项config.stopBubbling=true指明lombok的根目录为当前配置文件所在目录
config.stopBubbling = true
配置文件是分层的,原则是接近源文件的配置设置优先。在根目录的子目录中可以创建lombok.config配置文件,来覆盖根目录的配置文件(只覆盖配置项相同的配置,其他继承根目录的配置,若没有显式配置则使用默认值)
查看支持的特性
查看当前版本的lombok所支持的配置项使用命令工具config(切换到lombok.jar所在目录或者运行时指定目录)
D:\Program Files\eclipse>java -jar lombok.jar config -g --verbose
##
## Key : config.stopBubbling
## Type: boolean
##
## Tell the configuration system it should stop looking for other configuration files (default: false).
##
## Examples:
#
# clear config.stopBubbling
# config.stopBubbling = [false | true]
#
……
cofing工具还可以查看某个配置文件所有的配置项
D:\Program Files\eclipse>java -jar lombok.jar config lombok.config
lombok.val.flagUsage = ERROR
D:\Program Files\eclipse>
一些配置项
lombok.accessors.chain
如果设置成true,以链式生成setter,由默认返回void转为返回this
修改lombok.config配置文件,添加两行
clear lombok.accessors.chain
lombok.accessors.chain=true
lombok.accessors.fluent
如果设置成true,使用不带前缀的简单方式生成setter和getter,即使用原始的字段名称省略get和set前缀
修改lombok.config配置文件,添加两行
clear lombok.accessors.fluent
lombok.accessors.fluent=true
对比上图也能看出字段chainTest生成的setter的区别
lombok.anyConstructor.suppressConstructorProperties
如果设置成true,跳过添加一个@java.bean.ConstructorProperties生成的构造器
修改配置文件,添加两行
clear lombok.anyConstructor.suppressConstructorProperties
lombok.anyConstructor.suppressConstructorProperties=true
lombok.log.fieldName
生成log字段,默认是log
修改配置文件,添加
clear lombok.log.fieldName
lombok.log.fieldName=mylog
lombok.(featureName).flagUsage
可以强制禁用或者不建议使用lombok的特性,配置关键字的值一般是error、warning、allow,默认一般是没有设置。
比如禁用val:在配置文件lombok.config(文件在项目根目录),内容如下
clear config.stopBubbling
config.stopBubbling = true
clear lombok.val.flagUsage
lombok.val.flagUsage=ERROR
再使用val时,提示错误
当前使用的版本所支持的所有配置可以参考(用法参考val的例子即可,不再一一列举)
java -jar lombok.jar config -g --verbose
# lombok.accessors.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.allArgsConstructor.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.anyConstructor.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.builder.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.cleanup.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.data.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.delegate.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.equalsAndHashCode.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.experimental.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.extensionMethod.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.fieldDefaults.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.fieldNameConstants.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.getter.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.getter.lazy.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.helper.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.log.apacheCommons.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.log.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.log.flogger.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.log.javaUtilLogging.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.log.jbosslog.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.log.log4j.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.log.log4j2.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.log.slf4j.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.log.xslf4j.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.noArgsConstructor.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.nonNull.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.onX.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.requiredArgsConstructor.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.setter.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.sneakyThrows.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.synchronized.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.toString.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.utilityClass.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.val.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.value.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.var.flagUsage = [WARNING | ERROR | ALLOW]
# lombok.wither.flagUsage = [WARNING | ERROR | ALLOW]
配置文件是分层的:任何配置设置都适用于该名录中的所有源文件,以及子目录中的所有源文件,但更接近源文件的配置设置优先。例如,如果有/projects/lombok.config
lombok.log.fieldName = allLog
和/projects/firstProject/lombok.config
lombok.log.fieldName = firstLog
使用@Log注解:除了在/projects/firstProject中的项目以firstLog作为字段名,各种@log将使用allLog而不是默认的log作为字段名
要恢复由父配置文件设置的配置键到缺省值,可以使用clear选项。例如,如果父配置文件已经配置了val发出警告的所有用法,那么您可以通过在其中包含一个lombok来关闭子目录的警告。配置文件:
clear lombok.val.flagUsage
一些配置键会采用列表的形式进行配置。使用 += 添加一个条目;使用 -= 删除一个单项
比如:要求定义的变量以m_开头,否则就会有警告
在lombok.config配置文件中添加
lombok.accessors.prefix += m_
对比这两个变量一个添加了前缀一个没有添加前缀,没有添加前缀的抛出一个警告。
在lombok.config配置文件中可以使用注释,任何#开始的行都被认为是注释
全局配置
防止lombok在父级目录中搜索配置文件,可用如下配置指定lombok根目录
config.stopBubbling = true
建议放在工作台目录或者项目目录
lombok可以添加@javax.annotation.Generated注解尽可能生成注释
lombok.addJavaxGeneratedAnnotation = true
不建议使用这个注释,jdk9破坏了该注释,而且可能不会被修复
注意:直到lombok2.0.0该设置默认是true
@Lombok.Generated注解:在可能的情况下,对所有生成的节点生成注释;对JaCoCo(内置支持),或者其他类型的检查器和代码覆盖工具非常有用
lombok.addLombokGeneratedAnnotation = true
@SuppressFBWarnings,如果您想在类文件上运行FindBugs的话,非常有用的。要启用这个特性,请确保在编译时findbugs在可执行路径中,并添加以下配置键
lombok.extern.findbugs.addSuppressFBWarnings = true
可以影响任何源文件的配置
这些配置键可以使lombok影响源文件,即使源文件中没有任何lombok注解
lombok.fieldDefaults.defaultPrivate = true
lombok.fieldDefaults.defaultFinal = true
开启这些选项意味着lombok将所有源文件的每个字段都设置为final和private,除非显式访问修饰符或注解来抵消这一行为。更多信息参阅@FieldDefaults
lombok.config配置系统
lombok特性(一)
lombok特性(二)
#介绍
lombok项目通过增加处理程序使java语言更加简洁和快速,帮助开发人员消除 Java 的冗长,尤其是对于简单的 Java 对象,在源码中不需要写一些通用的方法,但是在编译生成的字节码文件中会生成这些方法
#安装
下载 lombok.jar 它包含用于开发的API,作为IDE集成的安装程序
##eclipse
打开cmd控制台,运行lombok.jar
D:\下载>java -jar lombok.jar
如果无法正确确定IDE的安装位置,则可以手动指定位置
手工配置eclipse.ini可以能达到相同目的:在eclipse.ini中配置lombok.jar路径
##idea
打开IDEA的Setting –> 选择Plugins选项 –> 选择Browse repositories –> 搜索lombok –> 点击安装 –> 安装完成重启IDEA –> 安装成功
#注解
注解 | 描述 |
---|---|
val | 变量类型自动推算,用在局部变量前面,相当于将变量声明为final,只能用在局部变量或者foreach中,不能用于类变量 |
var | 变量类型自动推算,用在局部变量前面,功能类似val,区别在于不声明变量为final |
@NonNull | 给方法参数增加这个注解会自动在方法内对该参数进行是否为空的校验,如果为空,则抛出NPE(NullPointerException) |
@Cleanup | 自动管理资源,用在局部变量之前,在当前变量范围内即将执行完毕退出之前会自动清理资源,自动生成try-finally这样的代码来关闭流 |
@Getter/@Setter | 用在属性上,再也不用自己手写setter和getter方法了,还可以指定访问范围 |
@ToString | 用在类上,可以自动覆写toString方法,当然还可以加其他参数,例如@ToString(exclude=”id”)排除id属性,或者@ToString(callSuper=true, includeFieldNames=true)调用父类的toString方法,包含所有属性 |
@EqualsAndHashCode | 用在类上,自动生成equals方法和hashCode方法 |
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor | 用在类上,自动生成无参构造和使用所有参数的构造函数以及把所有@NonNull属性作为参数的构造函数,如果指定staticName = “of”参数,同时还会生成一个返回类对象的静态工厂方法,比使用构造函数方便很多 |
@Data | 注解在类上,相当于同时使用了@ToString、@EqualsAndHashCode、@Getter、@Setter和@RequiredArgsConstrutor这些注解,对于POJO类十分有用 |
@Value | 用在类上,是@Data的不可变形式,相当于为属性添加final声明,只提供getter方法,而不提供setter方法 |
@Builder | 用在类、构造器、方法上,为你提供复杂的builder APIs,让你可以像如下方式一样调用Person.builder().name(“Adam Savage”).city(“San Francisco”).job(“Mythbusters”).job(“Unchained Reaction”).build();更多说明参考Builder |
@SneakyThrows | 自动抛受检异常,而无需显式在方法上使用throws语句 |
@Synchronized | 用在方法上,将方法声明为同步的,并自动加锁,而锁对象是一个私有的属性l o c k 或 lock或lock或LOCK,而java中的synchronized关键字锁对象是this,锁在this或者自己的类对象上存在副作用,就是你不能阻止非受控代码去锁this或者类对象,这可能会导致竞争条件或者其它线程错误 |
@Getter(lazy=true) | 可以替代经典的Double Check Lock样板代码 |
@Log | 根据不同的注解生成不同类型的log对象,但是实例名称都是log,有六种可选实现类 |
log六种实现 |
---|
@CommonsLog Creates log = org.apache.commons.logging.LogFactory.getLog(LogExample.class); |
@Log Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName()); |
@Log4j Creates log = org.apache.log4j.Logger.getLogger(LogExample.class); |
@Log4j2 Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class); |
@Slf4j Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class); |
@XSlf4j Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class); |
更多实现可以参考源码:git源码
#使用示例
非静态:静态是指由static关键字修饰的变量或方法;反之就是非静态。在java中,静态变量优于非静态量加载,所以如果静态代码块中不能引用非静态成员的变量,会报错。
非瞬态:瞬态是指关键字“transient”修饰的变量;反之为非瞬态。瞬态变量的生命周期仅存于调用者的内存中。瞬态变量不可被序列化。
以maven工程为例
引入依赖
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<scope>provided</scope>
</dependency>
多数例子都是以官网的例子为原型加工修改
可以使用class查看器,或者反编译工具查看编译后的文件内容,ide一般都提供该功能(或者装ide插件)
如果还不熟悉lombok.config的使用,请先异步至 lombok.config----lombok配置系统 因为下面的各注解有关介绍可能会涉及配置项,不再单独说明
##val
类型推导:val注解变量申明是final类型,根据类型自动推导出变量类型,只能用在方法或者构造函数的参数前面,不能用于类变量
package com.demo.lombok;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import lombok.val;
import lombok.var;
public class DemoValVar {
/*
* //下面的定义语句会有异常:Change type of "name" to "String"
* val name="xiaoming";
*/
public void lomboValMethod() {
val map = new HashMap<Integer, String>();
map.put(0, "zero");
map.put(5, "five");
for (val entry : map.entrySet()) {
System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
}
/*
* //定义下面这条语句会有异常:The final local variable map cannot be assigned. It must be blank and not using a compound assignment
* //说明是定义成final类型的变量
* map=new HashMap<Integer, String>();
*/
}
public void lomboVarMethod() {
var map = new HashMap<Integer, String>();
map.put(0, "zero");
map.put(5, "five");
for (var entry : map.entrySet()) {
System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
}
//定义下面的语句没有异常,说明是非final的
map=new HashMap<Integer, String>();
}
public static String getType(Object o){ //获取变量类型方法
return o.getClass().toString(); //使用类型的getClass()方法
}
public static String getModifier(Object o){ //获取变量类型方法
return Modifier.toString(o.getClass().getModifiers()); //使用类型的getClass()方法
}
public static void main(String[] args) {
DemoValVar demoValVar = new DemoValVar();
demoValVar.lomboValMethod();
demoValVar.lomboVarMethod();
}
}
可以结合lombok.config配置文件进行喜好设置:禁用、使用警告、允许(默认not set即允许)
lombok.val.flagUsage = [warning | error] (default: not set)
对于符合类型,通常都是推导出来父类,不是接口,例如表达式
bool ? new HashSet() : new ArrayList()
结果既是AbstractCollection 也是Serializable,结果推导是AbstractCollection,因为AbstractCollection是一个类,而Serializable是一个接口。当然也有歧义的时候,如当表达式推导结果是null或者Object的时候
##var
var是在lombok1.16.12引入的扩展功能,在2.0.0晋升到主包。
var的用法类似val,区别在于var定义的变量不是final的
可以结合lombok.config配置文件进行喜好设置:禁用、使用警告、允许(默认not set即允许)
lombok.var.flagUsage = [warning | error] (default: not set)
##NonNull
@NonNull注释用于指示对相应成员进行快速失败null-check的需要
- 在方法或构造函数的参数上使用@NonNull,lombok将生成一个null-check语句。
- 在字段上使用@NonNull,为字段赋值时(即调用字段的setter方法时),如果传的参数为null,则会抛出空异常NullPointerException,生成setter方法时会对参数是否为空检查
- 执行顺序在方法比较靠前的地方执行,比如构造函数,null-check会在显式声明this()或supper()的后面立即执行
- 如果已经有null-check,则不会有额外的null-check生成
package com.demo.lombok;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
@Getter
@Setter
public class DemoNonNull {
static final Logger logger = LoggerFactory.getLogger(DemoNonNull.class);
@NonNull
private String id;
public DemoNonNull(@NonNull String id) {
this.id = id;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DemoNonNull demoNonNull = null;
/*
* 下面的语句会抛出异常
* //demoNonNull= new DemoNonNull(null);
*/
demoNonNull = new DemoNonNull("1");
logger.info("demoNonNull.getId() :{}", demoNonNull.getId());
/*
* 下面的语句会抛出异常 //demoNonNull.setId(null);
*/
}
}
可以结合lombok.config配置文件进行喜好设置:禁用、使用警告、允许(默认not set即允许)
lombok.nonNull.flagUsage = [warning | error] (default: not set)
另外还可以设置抛出异常的类型
lombok.nonNull.exceptionType = [NullPointerException | IllegalArgumentException] (default: NullPointerException).
##@Cleanup
该注解使用在属性前,该注解是用来保证分配的资源被释放。在本地变量上使用该注解,任何后续代码都将封装在try/finally中,确保当前作用于中的资源被释放。默认@Cleanup清理的方法为"close()",可以使用注解的value指定不同的无参方法名称@Cleanup(“xxxx”)
- @Cleanup 不能调用有参清理函数,需要调用有参清理函数需要手工操作
- @Cleanup 如果清理方法抛出异常,它将抢占抛出方法体内的任何异常。这可能导致问题的实际原因被掩埋,因此在选择使用Project Lombok的资源管理时应该考虑这个问题
package com.demo.lombok;
import lombok.Cleanup;
import java.io.*;
public class CleanupExample {
public static void main(String[] args) throws IOException {
@Cleanup
InputStream in = new FileInputStream("c:\\test\\a.txt");
@Cleanup
OutputStream out = new FileOutputStream("b.txt");
byte[] b = new byte[10000];
while (true) {
int r = in.read(b);
if (r == -1)
break;
out.write(b, 0, r);
}
}
}
可以结合lombok.config配置文件进行喜好设置:禁用、使用警告、允许(默认not set即允许)
lombok.cleanup.flagUsage = [warning | error] (default: not set)
##@Getter和@Setter
该注解使用在类或者属性上,为字段生成Getter和Setter方法,可以注解到字段或者类上,默认是public类型的,如果需要的话可以修改方法的访问级别,使用AccessLevel.xxxxxx
AccessLevel.PUBLIC
AccessLevel.MODULE
AccessLevel.PROTECTED
AccessLevel.PACKAGE
AccessLevel.PRIVATE
AccessLevel.NONE
- 注解在类上会为类中的所有非静态成员变量生成Getter和Setter方法
- 非boolean类型:生成getXxxxx和setXxxx
- boolean类型:setXxxx和isXxxx
- 如果类和字段上均使用相同的注解,字段上的注解会覆盖相同的注解,以字段上的注解为准
- 如果注释字段所属的类包含与要生成的getter或setter相同名称的方法,则不管参数或返回类型如何,都不会生成相应的方法
- 可以通过AccessLevel.NONE禁用某个字段上的@Setter、@Getter、@Data
下面的截图中m_noneSetter字段没有生成对应的getter和setter(另外这个例子也演示了覆盖相同的注解)
package com.demo.lombok;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.java.Log;
@AllArgsConstructor
@Log
@Getter
@Setter
public class Tester {
private String m_test;
@Setter(AccessLevel.NONE)
@Getter(AccessLevel.NONE)
private String m_noneSetter;
}
##@ToString
生成toString()方法,默认情况下,它会以逗号分隔按顺序打印类名称以及每个字段(只会使用类中的非静态和非transient成员变量)。
设置lombok.toString.includeFieldNames =true 就可以控制字段的使用,默认是true,即开启状态
- 如果想从生成的方法中排除特定字段使用@ToString.Exclude注解该字段;当然也可以只使用特定的字段使用onlyExplicitlyIncluded = true和@ToString.Include注解
- 如果继承的有父类的话,可以设置callSuper 让其调用父类的toString()方法,例如:@ToString(callSuper = true)
package com.demo.lombok;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.ToString;
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Father {
private String m_father_first;
private String m_father_second;
}
package com.demo.lombok;
import lombok.AllArgsConstructor;
import lombok.ToString;
import lombok.extern.java.Log;
@AllArgsConstructor
@Log
@ToString(onlyExplicitlyIncluded = true,callSuper=true)
public class Tester extends Father{
Father father=new Father("father_first", "father_second");
private String m_first;
@ToString.Include
private String m_second;
@ToString.Include
private String m_third;
public static void main(String[] args) {
mylog.info(new Tester(new Father("father_first", "father_second"),"m_first","m_second","m_third").toString());
}
}
八月 14, 2018 6:04:47 下午 com.demo.lombok.Tester main
信息: Tester(super=Father(m_father_first=null, m_father_second=null), m_second=m_second, m_third=m_third)
父类也要有toString方法,不然打印的是对象内存地址
对于数组,在写 toString 方法时使用了 Arrays类的 静态方法 deepToString------这两个方法的区别是这样的,对于多维数组,使用 toString 只能打印出内部数组的名字,这时需要使用 deepToString 方法,它能将内部数组的内容全部打印出来
再来看看静态变量
package com.demo.lombok;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.ToString;
@ToString
@Log
public class ToStringExample {
private static final int STATIC_VAR = 10;
private String name;
private Shape shape = new Square(5, 10);
private String[] tags;
@ToString.Exclude
private int id;
static String spec="hide me";
String comm="show me";
public String getName() {
return this.name;
}
@ToString(callSuper = true, includeFieldNames = true)
public static class Square extends Shape {
private final int width, height;
public Square(int width, int height) {
this.width = width;
this.height = height;
}
}
public static void main(String[] args) {
ToStringExample toStringExample = new ToStringExample();
mylog.info("toStringExample.toString() :"+toStringExample.toString());
}
}
class Shape {
}
lombok.toString.includeFieldNames=true:默认的情况下lombok为每一个字段生成一对key=value返回给toString。如果这个设置被设置为false,lombok将省略该字段的名称,并简单地展开一个逗号分隔的所有字段值列表。如果显式指定includeFieldNames的话,优先级高于此设置。
lombok.toString.includeFieldNames = [true | false] (default: true)
修改lombok.config配置文件,增加如下设置
lombok.toString.includeFieldNames = false
package com.demo.lombok;
import lombok.AllArgsConstructor;
import lombok.ToString;
import lombok.extern.java.Log;
@AllArgsConstructor
@Log
@ToString
public class Tester extends Father{
private String m_first;
private String m_second;
private String m_third;
public static void main(String[] args) {
mylog.info(new Tester("m_first","m_second","m_third").toString());
}
}
八月 14, 2018 6:30:56 下午 com.demo.lombok.Tester main
信息: Tester(m_first, m_second, m_third)
开启includeFieldNames=true
@AllArgsConstructor
@Log
@ToString(includeFieldNames=true)
public class Tester extends Father{
private String m_first;
private String m_second;
private String m_third;
public static void main(String[] args) {
mylog.info(new Tester("m_first","m_second","m_third").toString());
}
}
八月 14, 2018 6:33:00 下午 com.demo.lombok.Tester main
信息: Tester(m_first=m_first, m_second=m_second, m_third=m_third)
在研究参数lombok.toString.doNotUseGetters的时候,发现无论如何设置,好像都不走getter,有哪位高手指点下,我在继续看看,若能解决我会更新本参数
lombok.toString.doNotUseGetters如果设置成true,lombok生成toString时直接访问字段而不是使用getter。如果注解doNotUseGetters显式声明,优先级高于该设置
lombok.toString.doNotUseGetters = [true | false] (default: false)
修改lombok.config,添加两行
clear lombok.toString.doNotUseGetters
lombok.toString.doNotUseGetters = true
@AllArgsConstructor
@Log
@ToString(onlyExplicitlyIncluded=true)
public class Tester extends Father{
private String m_first;
@ToString.Include
private String m_second;
private String m_third;
public void setM_second(String xString) {
System.err.println("doing");
this.m_second=xString;
}
public static void main(String[] args) {
mylog.info(new Tester("m_first","m_second","m_third").toString());
}
}
八月 14, 2018 6:44:43 下午 com.demo.lombok.Tester main
信息: Tester(m_second)
可以结合lombok.config配置文件进行喜好设置:禁用、使用警告、允许(默认not set即允许)
@EqualsAndHashCode
任何类使用@EqualsAndHashCode标注生成hashCode()和equals()方法,默认情况下,它将使用所有非静态,非transient字段。但可以通过在可选的@EqualsAndHashCode.Include 或者@EqualsAndHashCode.Exclude注解字段来排除或包含指定字段
- @EqualsAndHashCode.Exclude排除具体字段
- @EqualsAndHashCode.Include包含指定字段,需和属性onlyExplicitlyIncluded = true配合使用
package com.demo.lombok;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
@EqualsAndHashCode()
@Slf4j
public class EqualsAndHashCodeExample {
private transient int transientVar = 10;
private String name;
private double score;
@EqualsAndHashCode.Exclude
private Shape shape = new Square(5, 10);
private String[] tags;
@EqualsAndHashCode.Exclude
private int id;
public String getName() {
return this.name;
}
@EqualsAndHashCode(callSuper = true)
public static class Square extends Shape {
private final int width, height;
public Square(int width, int height) {
this.width = width;
this.height = height;
}
}
public static void main(String[] args) {
EqualsAndHashCodeExample equalsAndHashCodeExample = new EqualsAndHashCodeExample();
mylog.info("equalsAndHashCodeExample.hashCode() :{}",equalsAndHashCodeExample.hashCode());
}
}
lombok.equalsAndHashCode.doNotUseGetters设置为true,生成hashcode时lombok直接访问字段而不是访问getter,如果在注解中显式设置了doNotUseGetters参数,优先级高于配置文件中的lombok.equalsAndHashCode.doNotUseGetters配置
lombok.equalsAndHashCode.doNotUseGetters = [true | false] (default: false)
lombok.equalsAndHashCode.callSuper设置为call,如果继承了父类,lombok会实现父类的hashcode和equals,默认行为是skip,会产生一个警告
lombok.equalsAndHashCode.callSuper = [call | skip | warn] (default: warn)
可以结合lombok.config配置文件进行喜好设置:禁用、使用警告、允许(默认not set即允许)
lombok.equalsAndHashCode.flagUsage = [warning | error] (default: not set)
@NoArgsConstructor、 @RequiredArgsConstructor 、@AllArgsConstructor
给类增加无参构造器、指定参数的构造器、包含所有参数的构造器
- @NoArgsConstructor:使用在类上,提供一个无参构造器。当类中有final字段没有被初始化时,编译器会报错,此时可用@NoArgsConstructor(force = true),然后就会为没有初始化的final字段设置默认值 0 / false / null, 这样编译器就不会报错。对于具有约束的字段(例如@NonNull字段),不会生成检查或分配,因此请注意,正确初始化这些字段之前,这些约束无效
- @RequiredArgsConstructor:使用在类上,生成构造方法(可能带参数也可能不带参数),若带参数,只能是类中所有带有 @NonNull 注解的和以final修饰的未经初始化的字段
- @AllArgsConstructor:使用在类上,该注解提供一个全参数的构造方法,默认不提供无参构造。 这里的全参不包括已初始化的final字段哦~
- @RequiredArgsConstructor(staticName = “of”)会生成一个of()的静态方法,并把构造方法设置为私有的
- 这三个注解都会忽略static变量,另外会有一@java.beans.ConstructorProperties注解的构造函数,且至少有一个参数,它的作用是提供修改构造函数的一个桥接
package com.demo.lombok;
import lombok.AllArgsConstructor;
@AllArgsConstructor(staticName="allargs")
public class Tester{
private String m_first;
}
反编译后
package com.demo.lombok;
public class Tester
{
private String m_first;
public static Tester allargs(String m_first)
{
return new Tester(m_first);
}
private Tester(String first)
{
this.m_first = first;
}
}
package com.demo.lombok;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@NoArgsConstructor(force = true)
@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class ConstructorExample<T> {
private int x, y;
final int z=3;
final int unInit;
@NonNull
private T description;
public static void main(String[] args) {
ConstructorExample<String> constructorExampleNoArgs = new ConstructorExample<String>();
ConstructorExample<String> constructorExampleRequiredArgs = new ConstructorExample<String>(4, "desc");
ConstructorExample<String> constructorExampleAllArgs = new ConstructorExample<String>(1, 2, 4, "desc");
}
}
贴上反编译后的文件,结合上面的文字描述理解
package com.demo.lombok;
import lombok.NonNull;
public class ConstructorExample<T>
{
private int x;
private int y;
public ConstructorExample()
{
this.unInit = 0;
}
private ConstructorExample(int unInit, @NonNull T description)
{
if (description == null) {
throw new NullPointerException("description is marked @NonNull but is null");
}
this.unInit = unInit;this.description = description;
}
public static <T> ConstructorExample<T> of(int unInit, @NonNull T description)
{
return new ConstructorExample(unInit, description);
}
protected ConstructorExample(int x, int y, int unInit, @NonNull T description)
{
if (description == null) {
throw new NullPointerException("description is marked @NonNull but is null");
}
this.x = x;this.y = y;this.unInit = unInit;this.description = description;
}
final int z = 3;
final int unInit;
@NonNull
private T description;
public static void main(String[] args)
{
ConstructorExample<String> constructorExampleNoArgs = new ConstructorExample();
ConstructorExample<String> constructorExampleRequiredArgs = new ConstructorExample(4, "desc");
ConstructorExample<String> constructorExampleAllArgs = new ConstructorExample(1, 2, 4, "desc");
}
}
lombok.anyConstructor.suppressConstructorProperties 如果设置成true,lombok不生成@java.beans.ConstructorProperties注解的构造函数
lombok.anyConstructor.suppressConstructorProperties = [true | false] (default: false)
【注意】经过试验,默认不配置的时候并没有生成@ConstructorProperties标注的构造函数,只有当在lombok.config中显式配置为false的时候才生成,暂时没有找到原因(找到原因后修正mark一下)
对比下面的demo和本小节的第一段代码反编译的结果(类是相同的类)
修改lombok.config配置文件,添加
clear lombok.anyConstructor.suppressConstructorProperties
lombok.anyConstructor.suppressConstructorProperties = false
package com.demo.lombok;
import lombok.AllArgsConstructor;
@AllArgsConstructor(staticName="allargs")
public class Tester{
private String m_first;
}
package com.demo.lombok;
import java.beans.ConstructorProperties;
public class Tester
{
private String m_first;
public static Tester allargs(String m_first)
{
return new Tester(m_first);
}
@ConstructorProperties({"first"})
private Tester(String first)
{
this.m_first = first;
}
}
可以结合lombok.config配置文件进行喜好设置:禁用、使用警告、允许(默认not set即允许)
lombok.anyConstructor.flagUsage = [warning | error] (default: not set)
lombok.[allArgsConstructor|requiredArgsConstructor|noArgsConstructor].flagUsage = [warning | error] (default: not set)
@Data
- @Data 包含了 @ToString、@EqualsAndHashCode、@Getter / @Setter和@RequiredArgsConstructor的功能,如果显式地声明构造函数将不会生成新的构造函数。而且@Data不能设置callSuper, includeFieldNames 和exclude等,如果需要改变默认值,可以使用相应的注解
- getter和setter默认是public的,如果需要改变修饰符请使用@Setter和@Getter
- transient 类型的变量不会被hashcode和equals使用,静态变量也会被跳过
- 虽然@Data注解非常有用,但是它没有与其他注解相同的控制粒度。@Data提供了一个可以生成静态工厂的单一参数,将staticConstructor参数设置为所需要的名称,Lombok自动生成的构造函数设置为私有,并提供公开的给定名称的静态工厂方法@Data(staticConstructor=”of”)
- 同时使用@Data 和 @AllArgsConstructor 后 ,默认的无参构造函数失效,如果需要它,要重新设置 @NoArgsConstructor
package com.demo.lombok;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;
import lombok.ToString;
@Data
public class DataExample {
private final String name;
@Setter(AccessLevel.PACKAGE)
private int age;
private double score;
private String[] tags;
@ToString(includeFieldNames = true)
@Data(staticConstructor = "of")
public static class Exercise<T> {
private final String name;
private final T value;
}
}
可以结合lombok.config配置文件进行喜好设置:禁用、使用警告、允许(默认not set即允许)
lombok.data.flagUsage = [warning | error] (default: not set)
Value
- 该注解用于修饰类,是@Data的不可变形式,字段都被修饰为private和final,默认的情况下不会生成settter
- 默认类本身也是final的
- 实际上@Value等价于final @ToString @EqualsAndHashCode @AllArgsConstructor @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) @Getter
package com.demo.lombok;
import lombok.AccessLevel;
import lombok.ToString;
import lombok.Value;
import lombok.experimental.NonFinal;
import lombok.experimental.Wither;
@Value
public class ValueExample {
String name;
@Wither(AccessLevel.PACKAGE)
@NonFinal
int age;
double score;
protected String[] tags;
@ToString(includeFieldNames = true)
@Value(staticConstructor = "of")
public static class Exercise<T> {
String name;
T value;
}
}
反编译后的文件:
package com.demo.lombok;
import java.util.Arrays;
public final class ValueExample
{
private final String name;
private int age;
private final double score;
protected final String[] tags;
public ValueExample(String name, int age, double score, String[] tags)
{
this.name = name;this.age = age;this.score = score;this.tags = tags;
}
public String toString()
{
return "ValueExample(name=" + this.name + ", age=" + this.age + ", score=" + this.score + ", tags=" + Arrays.deepToString(this.tags) + ")";
}
public int hashCode()
{
int PRIME = 59;int result = 1;Object $name = this.name;result = result * 59 + ($name == null ? 43 : $name.hashCode());result = result * 59 + this.age;long $score = Double.doubleToLongBits(this.score);result = result * 59 + (int)($score ^ $score >>> 32);result = result * 59 + Arrays.deepHashCode(this.tags);return result;
}
public boolean equals(Object o)
{
if (o == this) {
return true;
}
if (!(o instanceof ValueExample)) {
return false;
}
ValueExample other = (ValueExample)o;Object this$name = this.name;Object other$name = other.name;
if (this$name == null ? other$name != null : !this$name.equals(other$name)) {
return false;
}
if (this.age != other.age) {
return false;
}
if (Double.compare(this.score, other.score) != 0) {
return false;
}
return Arrays.deepEquals(this.tags, other.tags);
}
public static final class Exercise<T>
{
private final String name;
private final T value;
public String toString()
{
return "ValueExample.Exercise(name=" + this.name + ", value=" + this.value + ")";
}
public static <T> Exercise<T> of(String name, T value)
{
return new Exercise(name, value);
}
private Exercise(String name, T value)
{
this.name = name;this.value = value;
}
public int hashCode()
{
int PRIME = 59;int result = 1;Object $name = this.name;result = result * 59 + ($name == null ? 43 : $name.hashCode());Object $value = this.value;result = result * 59 + ($value == null ? 43 : $value.hashCode());return result;
}
public boolean equals(Object o)
{
if (o == this) {
return true;
}
if (!(o instanceof Exercise)) {
return false;
}
Exercise<?> other = (Exercise)o;Object this$name = this.name;Object other$name = other.name;
if (this$name == null ? other$name != null : !this$name.equals(other$name)) {
return false;
}
Object this$value = this.value;Object other$value = other.value;return this$value == null ? other$value == null : this$value.equals(other$value);
}
}
}
可以结合lombok.config配置文件进行喜好设置:禁用、使用警告、允许(默认not set即允许)
lombok.value.flagUsage = [warning | error] (default: not set)
@Builder
@Builder注释为你的类生成复杂的构建器API,它把我们的Bean类包装为一个构建者模式,编译时增加了一个Builder内部类和全字段的构造器。
使用方式:Xxx.builder().name(“Adam Savage”).city(“San Francisco”).job(“Mythbusters”).job(“Unchained Reaction”).build();
@Builder可以放置在类上,构造方法上和普通方法上
在方法上使用@Builder,会生成以下事件
- 生成一个名为XxxBuilder(Xxx为类名)的内部静态类,与静态方法builder的返回类型相同
- 在builder方法中,针对目标的每个参数都是一个私有非静态非final的
- 在bulider方法中,有一个无参的私有构造函数
- 在bulider方法中,每个参数都有一个类似setter的方法,且返回类型是XxxBuilder
- 在bulider方法中,一个build()方法,返回类型是目标类型Xxx
- 在bulider方法中,具有一个toString()方法
- 目标方法中调用builder()产生新的builder
如果其中有字段或参数没有初始化,它们一直是0、null、false。如果@Builder放在类上(而不是放在方法和构造方法上)可以在字段上直接使用@Builder.Default指定默认值
如果使用注解@Singular注解一个参数(@Builder注解方法或构造方法)或者一个字段(@Builder注解类),lombok将作为集合处理builder,生成两个adder方法而不是一个setter
package com.demo.lombok;
import java.util.Set;
import lombok.Builder;
import lombok.Singular;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
@Builder
@ToString
@Slf4j
public class BuilderExample {
@Builder.Default
private long created = System.currentTimeMillis();
private String name;
private int age;
@Singular
private Set<String> occupations;
public static void main(String[] args) {
BuilderExample builderExample = BuilderExample.builder().age(1).name("test").build();
mylog.info("builderExample.toString() : {}",builderExample.toString());
}
}
反编译的老长了~ 读者自己反编译一下不贴了
@SneakyThrows
该注解的作用是将检查异常包装为运行时异常,那么编码时就无需处理异常了。自动抛受检异常, 而无需显式在方法上使用throws语句。把checked异常转化为unchecked异常,好处是不用再往上层方法抛出了
提示:这并不是友好的编码方式,因为你编写的api的使用者,不能显式的获知需要处理检查异常
package com.demo.lombok;
import java.io.UnsupportedEncodingException;
import lombok.SneakyThrows;
public class SneakyThrowsExample implements Runnable {
@SneakyThrows(UnsupportedEncodingException.class)
public String utf8ToString(byte[] bytes) {
return new String(bytes, "UTF-8");
}
@SneakyThrows
public void run() {
throw new Throwable();
}
}
可以结合lombok.config配置文件进行喜好设置:禁用、使用警告、允许(默认not set即允许)
lombok.sneakyThrows.flagUsage = [warning | error] (default: not set)
@Synchronized
这个注解用在类方法(static修饰)或者实例方法上,效果和synchronized关键字相同,区别在于锁对象不同,对于类方法和实例方法,synchronized关键字的锁对象分别是类的class对象和this对象,而@Synchronized得锁对象分别是私有静态final对象$LOCK和私有final对象$lock(如果字段不存在,则会创建),当然,也可以自己指定锁对象
给方法加上同步锁,如果直接指定了value=xxx,其中xxx为类的一个成员,那么该方法使用该成员xxx作为加锁对象,放在同步块中执行
package com.demo.lombok;
import lombok.Synchronized;
public class SynchronizedExample {
private final Object readLock = new Object();
@Synchronized
public static void hello() {
System.out.println("world");
}
@Synchronized
public int answerToLife() {
return 42;
}
@Synchronized("readLock")
public void foo() {
System.out.println("bar");
}
}
package com.demo.lombok;
import java.io.PrintStream;
public class SynchronizedExample
{
private final Object readLock = new Object();
private static final Object $LOCK = new Object[0];
public static void hello()
{
synchronized ($LOCK)
{
System.out.println("world");
}
}
private final Object $lock = new Object[0];
/* Error */
public int answerToLife()
{
……
}
public void foo()
{
synchronized (this.readLock)
{
System.out.println("bar");
}
}
}
可以结合lombok.config配置文件进行喜好设置:禁用、使用警告、允许(默认not set即允许)
lombok.synchronized.flagUsage = [warning | error] (default: not set)
@Getter(lazy=true)
@Getter(lazy = true)
标注字段为懒加载字段,懒加载字段在创建对象时不会进行真正的初始化,而是在第一次访问的时候才会初始化,后面再次访问也不会重复初始化
如果Bean的一个字段的初始化是代价比较高的操作,比如加载大量的数据;同时这个字段并不是必定使用的。那么使用懒加载机制,可以保证节省资源。
package com.demo.lombok;
import lombok.Getter;
public class GetterLazyExample {
@Getter(lazy = true)
private final double[] cached = expensive();
private double[] expensive() {
double[] result = new double[1000000];
for (int i = 0; i < result.length; i++) {
result[i] = Math.asin(i);
}
return result;
}
}
可以结合lombok.config配置文件进行喜好设置:禁用、使用警告、允许(默认not set即允许)
lombok.getter.lazy.flagUsage = [warning | error] (default: not set)
@Log
这个注解用在类上,可以省去从日志工厂生成日志对象这一步,直接进行日志记录,具体注解根据日志工具的不同而不同,同时,可以在注解中使用topic来指定生成log对象时的类名。不同的日志注解总结如下(上面是注解,下面是实际作用)
生成log对象,用于记录日志,可以通过topic属性来设置getLogger(String name)方法的参数 例如 @Log4j(topic = “com.xxx.entity.User”),默认是类的全限定名,即 类名.class,log支持以下几种:
注解 | 实际创建对象 |
---|---|
@CommonsLog | Creates private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LogExample.class); |
@Flogger | Creates private static final com.google.common.flogger.FluentLogger log = com.google.common.flogger.FluentLogger.forEnclosingClass(); |
@JBossLog | Creates private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(LogExample.class); |
@Log | Creates private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName()); |
@Log4j | Creates private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogExample.class); |
@Log4j2 | Creates private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class); |
@Slf4j | Creates private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class); |
@XSlf4j | Creates private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class); |
设置logger名字,默认是log
lombok.log.fieldName = an identifier (default: log).
默认情况下生成的logger是static,设置成false则是一个实例字段
lombok.log.fieldIsStatic = [true | false] (default: true)
可以结合lombok.config配置文件进行喜好设置:禁用、使用警告、允许(默认not set即允许)
lombok.log.flagUsage = [warning | error] (default: not set)
lombok.log.apacheCommons.flagUsage = [warning | error] (default: not set)
lombok.log.flogger.flagUsage = [warning | error] (default: not set)
lombok.log.jbosslog.flagUsage = [warning | error] (default: not set)
lombok.log.javaUtilLogging.flagUsage = [warning | error] (default: not set)
lombok.log.log4j.flagUsage = [warning | error] (default: not set)
lombok.log.log4j2.flagUsage = [warning | error] (default: not set)
lombok.log.slf4j.flagUsage = [warning | error] (default: not set)
lombok.log.xslf4j.flagUsage = [warning | error] (default: not set)
使用Lombok的注意事项
- 项目中要使用lombok 不仅ide要支持(否则一堆错误),项目中也要引入jar包
- 如果配置lombok.config文件,修改文件的属性值后,并不会自动重新编译class文件,ide编辑器也不会自动更新,所有每次修改配置文件后最后关闭java文件窗口重新打开,并且clean下项目
不足
- 当与基于注释的对象关系映射(ORM)框架结合使用时,数据类的注释数量可能开始变得笨拙。这很大程度上被Lombok注释取代的代码量所抵消。
- .java 文件无法再展示 .class 文件所包含的内容。
- 特定 Lombok 转换将根本地改变 Java 语法。@SneakyThrows 转换就是个明显的例子。它允许不在方法定义中声明所检查的异常,而将其扔掉,如同它们是未经检查的异常,给排查问题带来一定的障碍
@SneakyThrows
public void doSomething() {
throw new Exception();
}
还有一些扩展的特性,得空再写 可以参考官网