在不使用@NonNull的情况下使用Lombok @RequiredArgsConstructor [英] Use Lombok @RequiredArgsConstructor without @NonNull
问题描述
我有这样的东西:
@RequiredArgsConstructor
public class Person {
private String name;
private LocalDate date = null;
}
我只需要为name属性创建一个构造函数,但是它不起作用.如果我使用@NonNull
,它将构建所需的构造函数,但就我而言,名称应该可以为null,也不能为final.有任何想法吗?谢谢!
I need a constructor for the name attribute only, but it is not working. If I use @NonNull
it will build the constructor I need, but for my case the name should be able to be null, can not be final either. Any ideas? Thanks!
推荐答案
龙目岛@RequiredArgsConstructor
当前没有这样的选项.
Lombok @RequiredArgsConstructor
has no such option currently.
您至少有两个选择:
- 无需使用 lombok 注释.
-
使用继承-在您的情况下可能有点过分解决,但在某些情况下可能会很方便-如下所示:
- Just code the constructor
public Person(String name)
without help of lombok annotations. Use inheritance - which might be a bit overkill solution in your case but might be handy in some cases - as presented below:
-
创建一个基类,该基类包含您不想包含在
Person
构造函数中的所有字段:
Create a base class that holds all the fields you do not want to be in
Person
constructor:
public abstract class BasePerson {
private LocalDate date = null;
}
让您的Person
类在上面扩展您需要的构造函数中的字段,但也希望通过@AllArgsConstructor
成为null
:
Let your Person
class extend above with the fields you need in constructor but want to be null
also, with @AllArgsConstructor
:
@AllArgsConstructor
public abstract class Person extends BasePerson {
private String name;
}
这篇关于在不使用@NonNull的情况下使用Lombok @RequiredArgsConstructor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!