最全的 lombok 注解详情(随着版本不定时更新)
一、注解介绍
作用于类,覆盖默认的 equals 和 hashCode
二、属性介绍
- exclude:通过该属性可以排除某些字段
- of:通过该属性可以限定计算某些字段
当 of 属性和 exclude 属性同时出现时,of 属性优先。在不久的将来两者将会被加上 @Deprecated(不建议使用,有更好的替代) - callSuper:是否需要调用父类的方法,默认为 false
- doNotUseGetters:是否调用 getter 方法获取属性值,false 表示调用,默认 false
- cacheStrategy:是否缓存 hashcode,默认值 CacheStrategy.NEVER,不缓存
设置为 LAZY 时,第一次调用 hashcode 方法会对 hashcode 值进行缓存,下次再调用,返回缓存的 hashcode,无需重新计算 - onParam:列出的任何注解都放在生成的方法参数上
JDK 7 之前的写法是 onParam = @__({@NonNull}),而 JDK 8 之后的写法是 onParam_ = {@NonNull} - onlyExplicitlyIncluded:仅包含显式标记为 @ToString.include 的字段和方法,默认为 false
- Include:配置在中呈现此成员的方式;如果在方法上,则在输出中包含该方法的返回值,of 属性的替代
Include 只有在 onlyExplicitlyIncluded = true 时才会生效,Include 标记在需要包含的属性或方法上
当 onlyExplicitlyIncluded = true 时,则必须搭配 Include 使用,否则不包含任何字段- replaces:
- rank:rank 表示该字段的优先级,值越大排在越前面,默认为 0
- Exclude:exclude 属性的替代
- of、exclude 属性不能与 onlyExplicitlyIncluded、Include、Exclude 同时出现
三、实战演练
@EqualsAndHashCode(
exclude = {
"age"}, of = {
"name", "age"}, callSuper = false,
doNotUseGetters = false, cacheStrategy = CacheStrategy.NEVER, onParam_ = {
@NonNull}
)
public class 陈都灵 {
private String name;
private String age;
}
@EqualsAndHashCode(
callSuper = false, doNotUseGetters = false, cacheStrategy = CacheStrategy.NEVER,
onParam_ = {
@NonNull}, onlyExplicitlyIncluded = true // onlyExplicitlyIncluded 默认值为 false
)
public class 陈都灵 {
@EqualsAndHashCode.Include(replaces = "duling", rank = 0)
private String name;
@EqualsAndHashCode.Exclude
private String age;
}
四、温馨提示
当 onlyExplicitlyIncluded = true 时需要搭配 @ToString.Include 使用,这个时候就没有必要用 @ToString.Exclude,因为字段不加 @ToString.Include 将都不会显示