自动生成装箱通用类型的构建器模式

Automatic generation of builder pattern that boxes generic type

命令由 Builder 实例化,当设置值时,将它们包装在未定义的 object 中(然后仅当设置了 newTitle 时才在 execute 方法中使用它来设置书名).

命令class:

public class UpdateBookCommand {
  Book book;
  Undefined<String> newTitle;

  public Book execute(){
    if(newTitle.isDefined())
      this.book.setTitle(this.newTitle.get());
    return this.book;
  }

  public static class Builder {
    Book book;
    Undefined<String> newTitle = Undefined.instance();

    public Builder(Book book) {
      this.book=book;
    }

    public Builder newTitle(String newTitle){
      this.newTitle=Undefined.of(newTitle);
    }
    
    public UpdateBookCommand build() {
      UpdateBookCommand command = new UpdateBookCommand();
      command.newTitle=this.newTitle;
      return command;
    }
  }
}

此模式运行良好,我打算将它用于我的所有命令,但需要大量样板代码,我想使用 Lombok @Builder 或 FreeBuilder 或任何其他代码生成工具自动生成这些代码,但我找不到如何自动生成未定义的包装器。

两种工具都会生成

public Builder newTitle(Undefined<String> newTitle)){
  this.newTitle=newTitle;
}

而不是

public Builder newTitle(String newTitle){
  this.newTitle=Undefined.of(newTitle);
}

有没有办法更改由 @Builder@Freebuilder 注释生成的代码模板,或者我可以使用的任何其他工具?

您可以使用 Lombok 的 @Builder 并自定义不符合您需求的部分。构建器中已经存在的任何内容 class 都将被 Lombok 默默地忽略,其他所有内容将照常生成。

在您的示例中,如下所示:

@Builder
public class UpdateBookCommand {
  Book book;
  Undefined<String> newTitle;

  public static class UpdateBookCommandBuilder {
    public Builder newTitle(String newTitle) {
      this.newTitle=Undefined.of(newTitle);
    }
  }
  // Your methods here.
}