Lombok: @Builder should respect @Nullable annotation

Created on 2 Feb 2018  路  4Comments  路  Source: projectlombok/lombok

Just like @Setter, @Builder should copy @Nullable annotation to the method that sets the value for the field.

For example, having this class:

@Builder
public class LombokNullable {
    @Nullable  private String stringValue;
}

Lombok generates:

public class LombokNullable {
    @Nullable  private String stringValue;

    @java.beans.ConstructorProperties({"stringValue"})
    LombokNullable(String stringValue) {
        this.stringValue = stringValue;
    }

    public static LombokNullableBuilder builder() {
        return new LombokNullableBuilder();
    }

    public static class LombokNullableBuilder {
        private String stringValue;

        LombokNullableBuilder() {
        }

        public LombokNullableBuilder stringValue(String stringValue) {
            this.stringValue = stringValue;
            return this;
        }

        public LombokNullable build() {
            return new LombokNullable(stringValue);
        }

        public String toString() {
            return "LombokNullable.LombokNullableBuilder(stringValue=" + this.stringValue + ")";
        }
    }

The method "public LombokNullableBuilder stringValue(String stringValue) {" should copy @Nullable annotation to the parameter:
public LombokNullableBuilder stringValue(@Nullable String stringValue) {

Without this, IntelliJ's null inspection will flag this as a warning:
LombokNullable.builder().stringValue(methodAnnotatedWithNullable()

Most helpful comment

There still is the problem that the annotations are not copied to the fields in the builder. This triggers the eclipse null analysis :-(

All 4 comments

The same should be done for @Nonnull annotations.
Further .builder() and .build() should be @Nonnull too.

Fixed in latest edge, thanks to @wmdietl :)

https://projectlombok.org/download-edge

There still is the problem that the annotations are not copied to the fields in the builder. This triggers the eclipse null analysis :-(

error: [NullAway] assigning @Nullable expression to @NonNull field
@Builder

Was this page helpful?
0 / 5 - 0 ratings