在不使用@NonNull的情况下使用Lombok @RequiredArgsConstructor [英] Use Lombok @RequiredArgsConstructor without @NonNull

查看:928
本文介绍了在不使用@NonNull的情况下使用Lombok @RequiredArgsConstructor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的东西:

@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.

您至少有两个选择:

  1. 无需使用注释.
  2. 使用继承-在您的情况下可能有点过分解决,但在某些情况下可能会很方便-如下所示:

  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:

  • 创建一个基类,该基类包含您不想包含在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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆