1

Lombok Builder: Build object only if any one field is non null otherwise don't build object

@Builder
public class InterestLimit{
    String field1;
    String field2;
}
Pankaj Mandale
  • 596
  • 7
  • 15
  • Duplicate of https://stackoverflow.com/q/44855981/1538176 – Felix Jun 17 '22 at 07:42
  • Does this answer your question? [Lombok builder to check non null and not empty](https://stackoverflow.com/questions/44855981/lombok-builder-to-check-non-null-and-not-empty) – Felix Jun 17 '22 at 07:43

1 Answers1

3

You can annotate a constructor with the @Builder annotation. In there, you can validate the input.


public class InterestLimit {
    String field1;
    String field2;

    @Builder
    public InterestLimit(String f1, String f2) {
        if (f1 == null && f2 == null)
            throw new IllegalArgumentException();
        this.field1 = f1;
        this.field2 = f2;   
    }
}

Please also look into the documentation to fully understand the @Builder annotation:

Another way is to specify the build method, as seen in this post:

@AllArgsConstructor
@Builder
public class InterestLimit {
    String field1;
    String field2;

    public static class InterestLimitBuilder {
        public InterestLimit build() {
            if (field1 == null && field2 == null)
                throw new IllegalArgumentException();
            return new InterestLimit(field1, field2);
        }
    }
}
Jan Rieke
  • 7,027
  • 2
  • 20
  • 30
Felix
  • 123
  • 2
  • 12