Java Lombok:如何指定一个 arg 构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27547171/
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
Lombok: How to specify a one arg constructor?
提问by barbara
Using Lombok, is it possible to specify a one arg constructor?
使用 Lombok,是否可以指定一个 arg 构造函数?
My intention is to use Lombok annotations to create a constructor such as the one below.
我的目的是使用 Lombok 注释来创建一个构造函数,如下所示。
class MyClass {
private String param;
private Integer count;
public MyClass(String param) {
this.param = param;
}
}
采纳答案by KnutKnutsen
I didn't find in documentation
我在文档中没有找到
How about this: http://projectlombok.org/features/Constructor.html?
这个怎么样:http: //projectlombok.org/features/Constructor.html?
You have to initialize all variables which should not be part of the constructor.
您必须初始化所有不应属于构造函数的变量。
@RequiredArgsConstructor generates a constructor with 1 parameter for each field that requires special handling. All non-initialized final fields get a parameter, as well as any fields that are marked as @NonNull that aren't initialized where they are declared. For those fields marked with @NonNull, an explicit null check is also generated.
@RequiredArgsConstructor 为每个需要特殊处理的字段生成一个带有 1 个参数的构造函数。所有未初始化的 final 字段都获得一个参数,以及任何标记为 @NonNull 且未在声明位置初始化的字段。对于那些标有@NonNull 的字段,还会生成一个显式的空检查。
So the following should create an one argument (param
) constructor:
所以下面应该创建一个单参数 ( param
) 构造函数:
@RequiredArgsConstructor class MyClass {
private String param;
private Integer count = -1;
}
回答by maaartinus
Lombok doesn't let you to specify the fields exactly, but there are 3 annotations to choose from. With
Lombok 不允许您准确指定字段,但有 3 个注释可供选择。和
@RequiredArgsConstructor class MyClass {
private final String param;
private Integer count;
}
you can get it. An argument is requiredif it's not initialized inline and final
or @NonNull
.
你可以得到它。如果没有初始化 inline 和or ,则需要一个参数。final
@NonNull
回答by HarryCoder
@RequiredArgsConstructor
and @NonNull
are two important keys to solve the problem above. Because @RequiredArgsConstructor
creates a constructor with fields which are annotated by @NonNull
annotation.
@RequiredArgsConstructor
和@NonNull
是解决上述问题的两个重要关键。因为@RequiredArgsConstructor
创建了一个构造函数,其中的字段由@NonNull
注释注释。
@RequiredArgsConstructor
class MyClass {
@NonNull
private String param;
private Integer count;
}
This is equivalent to:
这相当于:
class MyClass {
private String param;
private Integer count;
public MyClass(String param) {
this.param = param;
}
}