今天在写一个小demo的时候要连续set属性,就突然想着能不能链式操作,试了一下发现还行,还挺好使,暂时也没发现有啥问题,后续可以用用看,下面是实体类和测试类:
pojo:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
private Date createTime;
private Date updateTime;
public User(String name, Integer age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
public User setCreateTime(Date createTime) {
this.createTime = createTime;
return this;//主要就是将自己作为返回值以便调用后续方法
}
public User setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
return this;
}
}
测试类:
void test(){
User user = new User();
user.setCreateTime(new Date()).setUpdateTime(new Date());//链式调用
System.out.println(user);
}
输出结果:
User(id=null, name=null, age=null, email=null, createTime=Sat Oct 24 00:06:40 CST 2020, updateTime=Sat Oct 24 00:06:40 CST 2020)