2 years ago

#63941

test-img

dawis11

Java records private constructor with builder

I have record:

@Schema(title = "Car")
public record CarResponse(
        @Schema(
        description = "The car name",
        example = "Audi") 
        @JsonProperty("carId") String id) {
}

and inner builder:

public static class Builder {
        private String id;

        public Builder withId(String id) {
            this.id = id;
            return this;
        }
 
        public CarResponse build() {
            return new CarResponse(id);
        }
}

In this case, the problem is that my CarResponse constructor using record is public rather than private. Having a class and a builder to make a private constructor is not a problem, but what should be done in this case to hide the public constructor?

Maybe one of the options builder put in the record, but in that case I lose the opportunity to add the swagger documentation on all fields.

java

builder

java-17

java-record

0 Answers

Your Answer

Accepted video resources