可选的 Lombok 自定义构建方法表示无法引用非静态变量

Optional with Lombok custom build method says non-static variable cannot be referenced

给定以下代码。

@Getter
@Builder(builderClassName = "Builder", buildMethodName = "build")
public final class BusinessEvent implements BusinessPayload {
  private String action, duration, outcome, provider, trackId, sequence;
  @lombok.Builder.Default private Optional<String> brand, vin, externalTrackId, code = Optional.empty();
  @lombok.Builder.Default private Optional<BusinessEventError> eventError = Optional.empty();

  static class Builder {
    BusinessEvent build() throws MissingRequiredValueException {
      // Custom validation
      return new BusinessEvent(action, duration, outcome, provider, trackId, sequence, brand, vin, externalTrackId, code, eventError);
    }
  }
}

我收到错误

java: non-static variable eventError cannot be referenced from a static context

在这种情况下,lombok 无法正确处理可选值?我在所有构建器中都看到了同样的问题。这不是由 intellij 插件显示为问题,而是仅在我尝试构建时显示。

我知道你不应该使用可选字段值,但在这种情况下,它使 API 更清晰,并且构建器无论如何都不会被序列化,我们有 DTO。

总结一下你想做什么:

  • 你想要一个由 lombok 生成的构建器
  • 您希望使用 @Default
  • 在构建器中分配默认值
  • 您希望在构建方法中进行自定义验证

这似乎不起作用。既不与 Optional 一起,也不与其他对象一起。好像是lombok的限制。

IntelliJ 未将其识别为错误的事实并不意味着它应该可以工作。但是你的编译失败了。这是一个真正的问题。

考虑以下代码,没有 @lombok.Builder.Default 注释:

@Getter
@Builder(builderClassName = "Builder", buildMethodName = "build")
public final class BusinessEvent {
    private String action, duration, outcome, provider, trackId, sequence;
    private Optional<String> brand, vin, externalTrackId, code = Optional.empty();
    private Optional<Object> eventError = Optional.empty();

    static class Builder {
        BusinessEvent build() {
            if (brand == null) {
                throw new RuntimeException("brand not set");
            }
            // Custom validation
            return new BusinessEvent(action, duration, outcome, provider, trackId, sequence, brand, vin, externalTrackId, code, eventError);
        }
    }

    public static void main(String[] args) {
        BusinessEvent eventWithBrand = BusinessEvent.builder().brand(Optional.of("brand")).build();
        // will throw exception
        BusinessEvent event = BusinessEvent.builder().build();
    }
}