1

Given the following object

@Getter
@Builder
@RequiredArgsConstructor
class Example {
    private final String maybeA;
    private final String maybeB;
}

Is it possible to add a constraint where one of these fields has to exist?

So we can have A and B, A or B, but not A nor B.

user18375257
  • 151
  • 1
  • 5
  • 1
    Can both exist? Or must *exactly* one be non-null? If it's the latter, you're probably looking for a sealed class with two subclasses for the two cases. If both can exist but at least one must, then I don't think Lombok can help you and you'll just need to have an explicit check in your constructor. – Silvio Mayolo Nov 28 '22 at 17:10
  • If I solved this problem in the language with another type system, I would determine the type that meets your requirements, and would use one field of this type instead of two `String maybe_`. I'm not sure that this approach is possible in Java – chptr-one Nov 28 '22 at 17:15
  • @SilvioMayolo yes both can exist. That's a shame it's probably not possible. But thanks for the response – user18375257 Nov 28 '22 at 17:39

2 Answers2

0

You can use @AssertFalse, an annotation of the package javax.validation.constraints :

@Getter
@Builder
@RequiredArgsConstructor
class Example {
    private final String maybeA;
    private final String maybeB;

    @AssertFalse
    private boolean oneFieldHasToExists() {
        return maybeA == null && maybeB == null;
    }
}
Maneki
  • 307
  • 2
  • 4
0

Something like:

@Getter
class Example {
    private final String maybeA;
    private final String maybeB;

    @Builder
    public Example(String maybeA, String maybeB) {
       if (maybeA == null && maybeB == null) {
          throw IllegalArgumentException("...");
       }
       this.maybeA = maybeA;
       this.maybeB = maybeB;
    }
}
Andrey B. Panfilov
  • 4,324
  • 2
  • 12
  • 18