Reputation: 616
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;
}
Upvotes: 2
Views: 4607
Reputation: 135
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);
}
}
}
Upvotes: 4