Java 中的链式编程

前言

​ 在写项目的时候,有一个实体类有好多个属性,new 出来之后需要不停的使用setXXX( )方法,效率低而且代码可读性差,查询了下发现可以实现实体类的链式编程。

public class User {
    private Integer id;
    private String userName;
    private String password;
    private String nikeName;
    private String email;
    private String phoneNum;

    /**
    setter/getter方法省略
    */
}
  • 测试类中的赋值操作
User user = new User();
user.setId(1);
user.setEmail("xxxx");
user.setUserName("test");
user.setPassword("5454");
user.setNikeName("swds");
user.setPhoneNum("17575");

一、 在setter方法中实现链式编程

  • 修改setter方法的返回值为实体类类型,添加return this; 语句
public class User {
    private Integer id;
    private String userName;
    private String password;
    private String nikeName;
    private String email;
    private String phoneNum;

    public Integer getId() {
        return id;
    }

    public User setId(Integer id) {
        this.id = id;
        return this;
    }

    public String getUserName() {
        return userName;
    }

    public User setUserName(String userName) {
        this.userName = userName;
        return this;
    }

    public String getPassword() {
        return password;
    }

    public String getNikeName() {
        return nikeName;
    }

    public User setNikeName(String nikeName) {
        this.nikeName = nikeName;
        return this;
    }

    public String getEmail() {
        return email;
    }

    public User setEmail(String email) {
        this.email = email;
        return this;
    }

    public String getPhoneNum() {
        return phoneNum;
    }

    public User setPhoneNum(String phoneNum) {
        this.phoneNum = phoneNum;
        return this;
    }

    public User setPassword(String password) {
        this.password = password;
        return this;
    }
}
  • 在测试类中实现了链式编程
User user = new User();
user.setId(1).setUserName("sdd").setPhoneNum("sdsd").setNikeName("dsdsd").setEmail("xxxxx").setPassword("122");

二、 使用lombok实现链式编程

  • 使用lombok之前,必须确保你的IDEA或者Eclipse中安装了lombok插件
  • 在项目中导入lombok的依赖
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
</dependency>

  • 在实体类上添加@Accessors(chain = true) 注解即可开启链式编程
@Accessors(chain = true)    // 开启链式编程
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    private String userName;
    private String password;
    private String nikeName;
    private String email;
    private String phoneNum;
    
}

posted @ 2020-06-30 01:14  江南夜未央  阅读(2418)  评论(0编辑  收藏  举报