聊聊lombok构造模式的参数校验

本文主要聊一下在lombok的builder模式下,如何进行参数校验。html

maven

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.16</version>
    <scope>provided</scope>
</dependency>

本文基于1.16.16版原本讲maven

lombok的builder实例

@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 &#64;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();

validation

那么问题来了,若是在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

doc

相关文章
相关标签/搜索