4

I have a project(ID3 tagging) that contains dozens of setters and getters. I'm investigating Project Lombok to see how it can help me.

Some of the fields that can be set have very strict requirements that could include character encoding, bit-setting, length checks, character ranges and, so on. I could use a builder patter but, there may be cases where the pattern isn't necessary. What if I want to use validation methods and/or classes rather than annotation? How can I access Lombok's setters in my Netbeans project to add these validations?

4

2 回答 2

4

简短的回答是你不能。

现在唯一支持的一致性检查是@Nonnull. 如果你想要其他任何东西,你必须手动编写你的设置器。显然,没有工具可以完成您列出的所有检查并通过注释描述它们充其量是繁琐的。

有时,此功能请求可能会有所帮助。对于您的需求,它可能过于粗略。很多时候,您所需要的只是手动编写一些设置器。此功能对不可变对象更有用,因为它将提供向生成的构造函数添加验证的唯一方法。

于 2014-06-10T10:05:43.690 回答
1

虽然目前无法对 setter 进行验证,但您可以在 lombok Builder 上进行自定义验证。

为此,您应该覆盖 Builder.build 方法并将您的验证放在那里。示例代码片段如下所示

@Getter
@EqualsAndHashCode
@ToString
@Builder(builderClassName = "Builder",buildMethodName = "build")
public class Customer {
    private long id;
    private String name;

    static class Builder {
        Customer build() {
            if (id < 0) {
                throw new RuntimeException("Invaid id");
            }
            if (Objects.isNull(name)) {
                throw new RuntimeException("name is null");
            }
            return new Customer(id, name);
        }
    }
}

来源和信用

于 2021-04-27T09:16:39.587 回答