注解类型 WithBy


@Target({FIELD,TYPE}) @Retention(SOURCE) public @interface 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)));
 
  • 嵌套类概要

    嵌套类
    修饰符和类型
    描述
    static @interface 
    已过时。
    永远不要使用此注解 - 阅读文档。
  • 可选元素概要

    可选元素
    修饰符和类型
    可选元素
    描述
    此处列出的任何注解都将放在生成的方法上。
    如果您希望您的 with 方法是非公开的,您可以在此处指定一个备用访问级别。
  • 元素详情

    • value

      如果您希望您的 with 方法是非公开的,您可以在此处指定一个备用访问级别。
      返回值
      该方法将使用此访问修饰符生成。
      默认
      PUBLIC
    • onMethod

      此处列出的任何注解都将放在生成的方法上。此功能的语法取决于 JDK 版本(对此我们无能为力;它是为了解决 javac 错误)。
      最高至 JDK7
      @With(onMethod=@__({@AnnotationsGoHere}))
      从 JDK8 起
      @With(onMethod_={@AnnotationsGohere}) // 注意 onMethod 后的下划线。
      返回值
      要应用于生成方法的注解列表。
      默认
      {}