简体   繁体   English

使用 lombok builder 获取字段值

[英]Get value of field with lombok builder

Is it possible to retrieve the value of a field on a builder which was generated by lombok?是否可以检索由 lombok 生成的构建器上的字段值?

final var builder = Something.builder();

try {
    // ... something that might break
}
catch (Throwable t) {
    builder.error("Something went wrong.");
    builder.success(false);
}

// don't continue if the builder is already marked as not-successful
if (builder.isSuccess() != null && builder.isSuccess()) {
 // ... do some more work / set more fields on the builder
}

return builder.build();

It seems that lombok builders do not expose getters for the fields they can build, so in the code above, builder.isSuccess() doesn't exist.似乎 lombok 构建器不会为他们可以构建的字段公开 getter,因此在上面的代码中, builder.isSuccess()不存在。 Is it possible to do this, or is it an anti-pattern?是否有可能做到这一点,或者它是一种反模式?

The alternative is to return from the catch block, but IMO multiple returns in a method lead to harder to follow code, so I would like to avoid that and just return the builder at the end of the method.另一种方法是从catch块返回,但 IMO 在一个方法中多次返回会导致更难遵循代码,所以我想避免这种情况,只在方法结束时返回构建器。

It's an antipattern.这是一种反模式。 Before command.build() your object is not consistent you shouldn't see its intermediate state, because the builder shouldn't have any getters.在 command.build() 之前,您的 object 不一致,您不应该看到它的中间 state,因为构建器不应该有任何吸气剂。 Before getting the field's value complete its creating.在获取字段的值之前完成它的创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM