简体   繁体   English

如何在 Project Lombok setter 中进行自定义验证

[英]How to make custom validations in Project Lombok setters

I have a project(ID3 tagging) that contains dozens of setters and getters.我有一个包含数十个 setter 和 getter 的项目(ID3 标记)。 I'm investigating Project Lombok to see how it can help me.我正在调查 Project Lombok 以了解它如何帮助我。

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?如何在 Netbeans 项目中访问 Lombok 的 setter 以添加这些验证?

The short answer is that you can't.简短的回答是你不能。

The only consistency check supported now is @Nonnull .现在唯一支持的一致性检查是@Nonnull If you want anything else, you have to write your setters manually.如果你想要别的东西,你必须手动编写你的 setter。 Obviously, no tool can do all the check you listed and describing them via annotations would be cumbersome at best.显然,没有任何工具可以完成您列出的所有检查,并且通过注释来描述它们充其量是很麻烦的。

Sometimes, this feature request could help.有时,此功能请求可能会有所帮助。 It might be too course grained for your needs or not.对于您的需要,它可能过于粗糙。 Quite often, all you need is to write some setters manually.通常,您只需要手动编写一些 setter。 This feature is more useful with immutable objects as it will provide the only way to add validation to generated constructors.此功能对于不可变对象更有用,因为它将提供向生成的构造函数添加验证的唯一方法。

Although validation on setters is not possible as of today but you can do custom validations on lombok Builder.尽管目前无法对 setter 进行验证,但您可以在 lombok Builder 上进行自定义验证。

To do this you should override Builder.build method and put your validations there.为此,您应该覆盖 Builder.build 方法并将您的验证放在那里。 Sample code snippet looks like below示例代码片段如下所示

@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);
        }
    }
}

source and credit 来源和信用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM