0

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.

dawis11
  • 820
  • 1
  • 9
  • 24
  • why do you think this can't work with a public constructor? I admit, bit of an odd design, but still – Stultuske Jan 18 '22 at 07:54
  • I don't want to leave the possibility to create an object with a constructor that has a lot of fields, I want the object to be created only through the builder – dawis11 Jan 18 '22 at 07:56
  • if you want to hide the generated constructor, make sure no constructor is being generated. – Stultuske Jan 18 '22 at 08:01
  • 2
    @Stultuske Unfortunately, this cannot be done. A record always has a generated constructor with all fields as arguments, and this constructor has the same visibility as the record declaration. – Seelenvirtuose Jan 18 '22 at 08:02
  • 1
    @dawis11 The only thing I can recommend is to use the _compact constructor_ and do the validation inside that. At the moment, I do not see another way. – Seelenvirtuose Jan 18 '22 at 08:04
  • 2
    @Seelenvirtuose Compactness has nothing to do with it; a compact constructor is just a shorthand for declaring the full canonical constructor, which you can also do. But yes, constructors is where invariant checking goes. – Brian Goetz Jan 18 '22 at 13:47
  • @BrianGoetz I know. Maybe I just wrote that in a misunderstanding way. I wanted to give a suggestion _and_ explain where to do it best. – Seelenvirtuose Jan 18 '22 at 16:38

0 Answers0