本文主要聊一下在lombok的builder模式下,如何進行參數校驗。html
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.16</version> <scope>provided</scope> </dependency>
本文基於1.16.16版原本講maven
@Data @Builder public class DemoModel { private String name; private int age; private int start; private int end; }
這個@Data,是個組合的註解,具體以下ide
/** * 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模式生成一個內部類,具體使用以下ui
DemoModel model = DemoModel.builder() .name("hello") .age(-1) .build();
那麼問題來了,若是在build方法調用,返回對象以前進行參數校驗呢。理想的狀況固然是lombok提供一個相似jpa的@PrePersist的鉤子註解呢,惋惜沒有。可是仍是能夠經過其餘途徑來解決,只不過須要寫點代碼,不是那麼便捷,多lombok研究深刻的話,能夠本身去擴展。code
@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。這樣就大功告成了。orm
上面的方法還不夠簡潔,能夠考慮深刻研究lombok進行擴展,實現相似jpa的@PrePersist的鉤子註解,更進一步能夠加入支持jsr303的validation註解。htm