2

给定以下代码。

@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: 不能从静态上下文引用非静态变量 eventError

在这种情况下,lombok 以某种方式无法正确处理可选值?我在所有建筑商中都看到了同样的问题。intellij 插件并未将其显示为问题,但仅在我尝试构建时才显示。

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

4

1 回答 1

2

总结一下你想做的事情:

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

这似乎不起作用。既不是可选的,也不是其他对象。似乎是龙目岛的限制。

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();
    }
}
于 2019-12-05T10:07:33.430 回答