Default value on null with Lombok or Spring Boot?

Viewed 384

I have some constructors like these where I must handle with parameters being null.

    public Element(int value1, String value2, String value3, String value4) {
        this.value1 = value1;
        this.value2 = value2 != null ? value2 : "";
        this.value3 = value3 != null ? value3 : "";
        this.value4 = value4 != null ? value4 : "";
    }

Yes I know, I could write a utility-method or my own annotation to reduce the boiler plate code for params 2,3,4

But is there any existing solution? Something like @DefaultOnNull("") on the parameter or even the class?

2 Answers

Thanks for all comments. I solved it this way to reduce the boiler plate code at least a little bit:

    public Element(int value1, String value2, String value3, String value4) {
        this.value1 = value1;
        this.value2 = Objects.requireNonNullElse(value2, "");
        this.value3 = Objects.requireNonNullElse(value3, "");
        this.value4 = Objects.requireNonNullElse(value4, "");
    }
Related