为object中使用builder预初始化的属性赋值,可以通过以下步骤进行:
以下是一个示例代码,演示了如何使用builder预初始化属性并为其赋值:
public class User {
private String name;
private int age;
private String email;
private User(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.email = builder.email;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
public static class Builder {
private String name;
private int age;
private String email;
public Builder(String name) {
this.name = name;
}
public Builder setAge(int age) {
this.age = age;
return this;
}
public Builder setEmail(String email) {
this.email = email;
return this;
}
public User build() {
return new User(this);
}
}
}
// 使用示例
User user = new User.Builder("John")
.setAge(30)
.setEmail("john@example.com")
.build();
System.out.println(user.getName()); // 输出 "John"
System.out.println(user.getAge()); // 输出 30
System.out.println(user.getEmail()); // 输出 "john@example.com"
在上述示例中,我们创建了一个User类,其中包含了预初始化的属性"name",并使用Builder模式为其赋值。通过调用builder对象的相应setter方法,我们可以为属性"age"和"email"赋值,并通过调用build方法生成最终的User对象。
领取专属 10元无门槛券
手把手带您无忧上云