猿问

龙目岛生成器方法返回类本身的实例,而不是返回生成器类

我有一个班级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);useruser.withLastName("Bob").withAge(31);


如何利用龙目岛来保存“withXXX”方法?@Builder不是为此用例设计的。


慕桂英546537
浏览 63回答 1
1回答

陪伴而非守候

试试这个:@Data@Builder@Accessors(fluent = true) // <— This is what you wantpublic class User {&nbsp; &nbsp; private final String firstName;&nbsp; &nbsp; private final String lastName;&nbsp; &nbsp; private final int age;}然后使用:User user = User.builder()&nbsp; &nbsp; .firstName("foo")&nbsp; &nbsp; .lastName("bar")&nbsp; &nbsp; .age(22)&nbsp; &nbsp; .build();稍后:user.setFirstName("baz").setAge(23); // fluent setters注意如何通过使所有字段变得不可变(最佳实践)。如果需要可变性,请删除关键字。Userfinalfinal
随时随地看视频慕课网APP

相关分类

Java
我要回答