2026-10-16 · Q&A guide

Using Lombok with Optional Fields in Java

Learn how to keep Lombok’s builder while exposing Optional getters without changing field types.

Why Lombok Generates a Getter

The @Value annotation automatically creates getters for every field. If the field type is String, the generated getter returns a String. When you want to expose an Optional, Lombok will only do that if the field itself is Optional, which forces the builder to accept Optional values.

Suppressing the Default Getter

Lombok allows you to disable the automatically generated getter for a single field. Apply @Getter(AccessLevel.NONE) to the field you want to customize. The rest of the class still benefits from Lombok’s convenience annotations.

@Value
public class Address {
    @NotNull String userId;
    @NotNull String line1;

    @Getter(AccessLevel.NONE)
    String line2;

    // custom getter below
}

Custom Optional Getter

Write a normal method that returns Optional<String>. Lombok will not override it because the default getter was suppressed. The method can simply wrap the underlying String field.

public Optional<String> getLine2() {
    return Optional.ofNullable(line2);
}

Builder Behavior

The @Builder annotation still creates a builder that accepts a raw String for line2. This matches the field type, so the builder remains simple and type‑safe. If you need a builder that accepts Optional, you would have to write a custom builder method, but that is rarely necessary.

Full Practical Example

Below is a minimal, compile‑ready snippet that demonstrates the pattern.

@Value
@Builder
public class Address {
    @NotNull String userId;
    @NotNull String line1;

    @Getter(AccessLevel.NONE)
    String line2;

    public Optional<String> getLine2() {
        return Optional.ofNullable(line2);
    }
}

Takeaway: Suppress Lombok’s getter for a field and write a custom Optional‑returning method to keep the builder simple.

People also ask

Do I need @Getter(AccessLevel.NONE) on the field?

Yes, otherwise Lombok will generate a conflicting getter.

Can I keep @Value and @Builder together?

Absolutely; Lombok supports both on the same class.

What if I want the builder to accept Optional?

Write a custom builder method that accepts Optional and assigns its value to the field.

Inspired by a public discussion on Stack Overflow. This article is an original explanation for learners.

← All posts