命令由生成器实例化,在设置值时,生成器将值包装在一个未定义的对象中(只有在设置了newTitle的情况下,才会在execute方法中使用该对象来设置书的标题)。
命令类:
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注释生成的代码模板,或者其他我可以使用的工具?
发布于 2020-09-20 20:03:18
您可以使用龙目岛的@Builder并定制不符合您需求的部分。构建器类中已经存在的任何内容都将被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.
}https://stackoverflow.com/questions/63912996
复制相似问题