Search code examples
javaconditional-statementsbuilder

Conditional setting of certain fields in a builder


I have a legacy Java class with a builder - I can't change this class.

Some of the setters of the builder are throwing an exception on null input:

     public Cat.Builder setOwnerName(String value) {
        if (value == null) {
            throw new NullPointerException();
        } else {
            this.ownerName = value;
            this.onChanged();
            return this;
        }
     }

I'm trying to create that Cat from another class - using an external object that may, or may not, have a null value in the relevant field:

  Cat cat = Cat.newBuilder()
            .setXYZ("XYZ")
            .setOwnerName(inputFromUser.getOwnerName())
            .build();

And since the inputFromUser.getOwnerName() is sometimes null, the builder throws an exception.

I'm trying to find an elegant way to conditionally set or not the ownerName (or any other of the non-null fields).


Solution

  • Cat.Builder builder = Cat.newBuilder()
        .setXYZ("XYZ");
    Optional.ofNullable(inputFromUser.getOwnerName())
        .ifPresent(builder::setOwnerName);
    // repeat above statement for all optional fields
    Cat cat = builder.build();