簡體   English   中英

Lombok 構建器方法返回類本身的實例而不是返回構建器類

[英]Lombok builder methods return the instance of the class itself instead of returning builder class

我有一個類User

public class User {
    private String firstName;
    private String lastName;
    private int age;

    public User withFirstName(String firstName) {
        this.firstName = firstName;
        return this;
    }

    public User withLastName(String lastName) {
        this.lastName = lastName;
        return this;
    }

    public User withAge(int age) {
        this.age = age;
        return this;
    }
}

所以我可以初始化它使用User user = new User().withFirstName("Tom").withAge(30); ,並且在user初始化之后,我仍然可以通過user.withLastName("Bob").withAge(31);修改它user.withLastName("Bob").withAge(31); .

如何利用 Lombok 來保存“withXXX”方法? @Builder 不是為這個用例設計的。

嘗試這個:

@Data
@Builder
@Accessors(fluent = true) // <— This is what you want
public class User {
    private final String firstName;
    private final String lastName;
    private final int age;
}

然后使用:

User user = User.builder()
    .firstName("foo")
    .lastName("bar")
    .age(22)
    .build();

然后:

user.setFirstName("baz").setAge(23); // fluent setters

注意如何User可以通過使所有領域進行不可變的(最佳實踐), final 如果你想變性,除去final關鍵字。

我試圖為流利的設置者返回新實例找到一個解決方案,以使該實例保持不變,並且我從Lombok實驗功能中找到了Wither注釋,並從穩定功能中找到了Value注釋。

希望對您有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM