使用lombok @Builder的必需参数 [英] Required arguments with a lombok @Builder

查看:2422
本文介绍了使用lombok @Builder的必需参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将 @Builder 添加到课程中。创建构建器方法。

If I add @Builder to a class. The builder method is created.

Person.builder().name("john").surname("Smith").build();

我需要特定字段。在这种情况下,名称字段是必需的,但姓氏不是。理想情况下,我想宣布它是这样的。

I have a requirement where a particular field is required. In this case, the name field is required but the surname is not. Ideally, I would like to declare it like so.

Person.builder("john").surname("Smith").build()

我无法弄清楚如何做到这一点。我已经尝试将@Builder添加到构造函数中,但它不起作用。

I can't work out how to do this. I have tried adding the @Builder to a constructor but it didn't work.

@Builder
public Person(String name) {
    this.name = name;
}


推荐答案

您可以轻松完成Lombok注释配置

You can do it easily with Lombok annotation configuration

import lombok.Builder;
import lombok.ToString;

@Builder(builderMethodName = "hiddenBuilder")
@ToString
public class Person {

    private String name;
    private String surname;

    public static PersonBuilder builder(String name) {
        return hiddenBuilder().name(name);
    }
}

然后就这样使用

Person p = Person.builder("Name").surname("Surname").build();
System.out.println(p);

当然 @ToString 是可选的。

这篇关于使用lombok @Builder的必需参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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