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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:34:35  来源:igfitidea点击:

Lombok: How to specify a one arg constructor?

javalombok

提问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 finalor @NonNull.

你可以得到它。如果没有初始化 inline 和or ,则需要一个参数。final@NonNull

回答by HarryCoder

@RequiredArgsConstructorand @NonNullare two important keys to solve the problem above. Because @RequiredArgsConstructorcreates a constructor with fields which are annotated by @NonNullannotation.

@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;
    }
}