java Lombok 中带有 @Builder 或 @Getter 注释的默认字段值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40314445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Default field value with @Builder or @Getter annotation in Lombok
提问by Hazel Troost
I'm using Lombok @Builder
annotation, but I'd like some of the String
fields to be optional and default to ""
to avoid NPEs. Is there an easy way to do this? I can't find anything.
我正在使用 Lombok@Builder
注释,但我希望某些String
字段是可选的并且默认""
为避免 NPE。是否有捷径可寻?我找不到任何东西。
Alternately, a way to customize @Getter
to return a default value if the variable is null
.
或者,@Getter
如果变量是null
.
采纳答案by JafarKhQ
Starting from version v1.16.16
they added @Builder.Default
.
从v1.16.16
他们添加的版本开始@Builder.Default
。
@Builder.Default
lets you configure default values for your fields when using@Builder
.
@Builder.Default
允许您在使用@Builder
.
example:
例子:
@Setter
@Getter
@Builder
public class MyData {
private Long id;
private String name;
@Builder.Default
private Status status = Status.NEW;
}
PS:Nice thing they also add warning in case you didn't use @Builder.Default
.
PS:好在他们还添加了警告,以防您没有使用@Builder.Default
.
Warning:(35, 22) java: @Builder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final.
警告:(35, 22) java: @Builder 将完全忽略初始化表达式。如果您希望初始化表达式用作默认值,请添加@Builder.Default。如果它不应该在构建过程中设置,请将字段设为 final。
回答by ntalbs
You have to provide the builder class like the below:
您必须提供如下所示的构建器类:
@Builder
public class XYZ {
private String x;
private String y;
private String z;
private static class XYZBuilder {
private String x = "X";
private String y = "Y";
private String z = "Z";
}
}
Then the default value for x
, y
, z
will be "X"
, "Y"
, "Z"
.
那么x
, y
,的默认值z
将是"X"
, "Y"
, "Z"
。
回答by JeanValjean
Another way to go is to use @Builder(toBuilder = true)
另一种方法是使用 @Builder(toBuilder = true)
@Builder(toBuilder = true)
public class XYZ {
private String x = "X";
private String y = "Y";
private String z = "Z";
}
and then you use it as follows:
然后按如下方式使用它:
new XYZ().toBuilder().build();
With respect to the accepted answer, this approach is less sensible to class renaming. If you rename XYZ
but forget to rename the inner static class XYZBuilder
, then the magic is gone!
关于公认的答案,这种方法对类重命名不太明智。如果您重命名XYZ
但忘记重命名内部静态类XYZBuilder
,那么魔法就消失了!
It's all up to to you to use the approach you like more.
使用您更喜欢的方法完全取决于您。