序
本文主要聊一下在lombok的builder模式下,如何进行参数校验。
maven
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.16</version>
<scope>provided</scope>
</dependency>复制代码
本文基于1.16.16版本来讲
lombok的builder实例
@Data
@Builder
public class DemoModel {
private String name;
private int age;
private int start;
private int end;
}复制代码
这个@Data,是个组合的注解,具体如下
/** * Generates getters for all fields, a useful toString method, and hashCode and equals implementations that check * all non-transient fields. Will also generate setters for all non-final fields, as well as a constructor. * <p> * Equivalent to {@code @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode}. * <p> * Complete documentation is found at <a href="https://projectlombok.org/features/Data.html">the project lombok features page for @Data</a>. * * @see Getter * @see Setter * @see RequiredArgsConstructor * @see ToString * @see EqualsAndHashCode * @see lombok.Value */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface Data { /** * If you specify a static constructor name, then the generated constructor will be private, and * instead a static factory method is created that other classes can use to create instances. * We suggest the name: "of", like so: * * <pre> * public @Data(staticConstructor = "of") class Point { final int x, y; } * </pre> * * Default: No static constructor, instead the normal constructor is public. */ String staticConstructor() default ""; }复制代码
@Builder会按builder模式生成一个内部类,具体使用如下
DemoModel model = DemoModel.builder() .name("hello") .age(-1) .build();复制代码
validation
那么问题来了,如果在build方法调用,返回对象之前进行参数校验呢。理想的情况当然是lombok提供一个类似jpa的@PrePersist的钩子注解呢,可惜没有。但是还是可以通过其他途径来解决,只不过需要写点代码,不是那么便捷,多lombok研究深入的话,可以自己去扩展。
@Data
@Builder
public class DemoModel {
private String name;
private int age;
private int start;
private int end;
private void valid(){
Preconditions.checkNotNull(name,"name should not be null");
Preconditions.checkArgument(age > 0);
Preconditions.checkArgument(start < end);
}
public static class InternalBuilder extends DemoModelBuilder {
InternalBuilder() {
super();
}
@Override
public DemoModel build() {
DemoModel model = super.build();
model.valid();
return model;
}
}
public static DemoModelBuilder builder() {
return new InternalBuilder();
}
}复制代码
这里通过继承lombok生成的builder(重写build()方法加入校验),重写builder()静态方法,来返回自己builder。这样就大功告成了。
小结
上面的方法还不够简洁,可以考虑深入研究lombok进行扩展,实现类似jpa的@PrePersist的钩子注解,更进一步可以加入支持jsr303的validation注解。