@With
创建一个新的对象,该对象是当前对象的副本,但某些字段的值可以被更改。
1、如何使用
- @With 可以使用在类上,也可以使用在成员变量上。加在类上相当于给所有成员变量 @With
- 可以配合AccessLevel使用,创建出指定访问修饰符的with方法。
2、代码示例
例:
@AllArgsConstructor
@ToString
@With(AccessLevel.PRIVATE)
public class People {
private String name;
private int age;
private String sex;
public static void main(String[] args) {
People p = new People("tom", 18, "男");
People p1 = p.withAge(19).withSex("女");
System.out.println(p.toString());
System.out.println(p1.toString());
}
}
编译后:创建出所有属性的with方法,并且访问修饰符为private,另外通过编译后的代码可以看出,with方法依赖有参构造方法,所以@With往往与@AllArgsConstructor共同使用。
public class People {
private String name;
private int age;
private String sex;
public static void main(String[] args) {
People p = new People("tom", 18, "男");
People p1 = p.withAge(19).withSex("女");
System.out.println(p.toString());
System.out.println(p1.toString());
}
@Generated
public People(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
@Generated
public String toString() {
return "People(name=" + this.name + ", age=" + this.age + ", sex=" + this.sex + ")";
}
@Generated
private People withName(String name) {
return this.name == name ? this : new People(name, this.age, this.sex);
}
@Generated
private People withAge(int age) {
return this.age == age ? this : new People(this.name, age, this.sex);
}
@Generated
private People withSex(String sex) {
return this.sex == sex ? this : new People(this.name, this.age, sex);
}
}
代码输出结果: