注解类型 WithBy
放在任何字段上,使 lombok 构建一个 'withBy' - 一个 withFieldNameBy 方法,该方法生成此对象的克隆(除了 1 个字段获得新值之外)。
完整文档请见 project lombok 中 @WithBy 的功能页面。
示例
private @WithBy final int foo; private @WithBy final String bar;将会生成
public SELF_TYPE withFooBy(@lombok.NonNull IntUnaryOperator operator) { int foo = operator.apply(this.foo); return this.foo == foo ? this : new SELF_TYPE(foo, bar); } public SELF_TYPE withBarBy(@lombok.NonNull Function<? super String, ? extends String> operator) { String bar = operator.apply(this.bar); return this.bar == bar ? this : new SELF_TYPE(foo, bar); }
此注解也可以应用于类,在这种情况下,就好像所有尚未具有 WithBy
注解的非静态字段都具有该注解。
此注解主要用于分层不可变数据结构。例如
class Movie { @WithBy private final Director director; } class Director { @WithBy private final LocalDate birthDate; }使用普通的
@With
,要将电影导演的出生日期增加一天,您需要编写movie = movie.withDirector(movie.getDirector().withBirthDate(movie.getDirector().getBirthDate().plusDays(1)));但是使用
@WithBy
,您需要编写movie = movie.withDirectorBy(d -> d.withBirthDateBy(bd -> bd.plusDays(1)));
-
嵌套类概要
嵌套类 -
可选元素概要
可选元素修饰符和类型可选元素描述此处列出的任何注解都将放在生成的方法上。如果您希望您的 with 方法是非公开的,您可以在此处指定一个备用访问级别。
-
元素详情
-
value
-
onMethod
WithBy.AnyAnnotation[] onMethod此处列出的任何注解都将放在生成的方法上。此功能的语法取决于 JDK 版本(对此我们无能为力;它是为了解决 javac 错误)。
最高至 JDK7
@With(onMethod=@__({@AnnotationsGoHere}))
从 JDK8 起
@With(onMethod_={@AnnotationsGohere})
// 注意onMethod
后的下划线。- 返回值
- 要应用于生成方法的注解列表。
- 默认
{}
-