Use Lombok @RequiredArgsConstructor without @NonNull

坚强是说给别人听的谎言 提交于 2019-12-24 14:19:31

问题


I have something like this:

@RequiredArgsConstructor
public class Person {
    private String name;
    private LocalDate date = null;
}

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!


回答1:


Lombok @RequiredArgsConstructor has no such option currently.

You have at least two options:

  1. Just code the constructor public Person(String name) without help of lombok annotations.
  2. Use inheritance - which might be a bit overkill solution in your case but might be handy in some cases - as presented below:

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


来源:https://stackoverflow.com/questions/48790494/use-lombok-requiredargsconstructor-without-nonnull

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!