Skip to content

[REQ] Optional getters for nullable fields only (opt-in, raw-type setters) #24002

@jorgerod

Description

@jorgerod

Is your feature request related to a problem? Please describe.

When generating Java DTOs, getters for nullable / non-required fields return the raw type, which can be null. This pushes null-safety to runtime: consumers must defensively guard against NullPointerException instead of being guided by the type system at compile time.

private BigDecimal amount;

public BigDecimal getAmount() {
    return amount; // can be null; no compile-time hint
}

Describe the solution you'd like

Add a new opt-in configuration option (e.g. optionalGettersForNullableFieldsOnly) for the java and spring generators that makes getters of nullable / non-required fields return Optional<T>, leaving the field and the setter with the raw type:

public Optional<PlanRequestPriceDTO> getPrice() {
    return Optional.ofNullable(this.price);
}

public void setPrice(PlanRequestPriceDTO price) {
    this.price = price;
}

Key points:

  • Disabled by default — existing behavior is unchanged unless the option is explicitly enabled.
  • Optional appears only on the getter return type, via Optional.ofNullable(...).
  • The field and setter parameter keep the raw type (no Optional), so there's no point where Optional.get() on an empty value could throw, and setters remain symmetric with classic JavaBeans (compatible with MapStruct, Jackson, binders, etc.).
  • Applies only to nullable / non-required fields, not all getters.

This mirrors what Apache Avro already offers through optionalGettersForNullableFieldsOnly in its avro-maven-plugin.

Describe alternatives you've considered

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions