java - Lombok 自定义构建方法可选,表示无法引用非静态变量
问题描述
给定以下代码。
@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。
解决方案
总结一下你想做的事情:
- 你想要一个由 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();
}
}
推荐阅读
- python - 如何将列表转换为使用元组作为键的字典
- node.js - 错误:未指定默认引擎,节点服务器中未提供扩展
- python - 在 Windows 10、python 3.6 和 anaconda 上使用 opencv-python
- font-awesome - 字体真棒图标丢失
- javascript - 如何在不同情况下在 javascript 中使用 html 表格“td”元素?
- r - 使用 plotly-R 更改 3d 散点图的边距
- java - Java JSCH - 在 exec 或 shell 通道中发送 EOF
- python - 为什么我的 python 函数更改系列对象的数据类型不起作用?
- mysql - 将数据库 A 中的表中的特定行插入数据库 B 中的另一个表
- function - 如何调试从 conky 调用的 lua 函数?