博客搬移到这里:http://yemengying.com/
有个本身的博客还蛮好玩的,bazinga!app
有一个有不少属性的类:函数
public class User { private int id; private String name; private int age; private int sex; private int cityId; private int buId; private int roleId; private String pinyinName; public String getPinyinName() { return pinyinName; } public void setPinyinName(String pinyinName) { this.pinyinName = pinyinName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public int getCityId() { return cityId; } public void setCityId(int cityId) { this.cityId = cityId; } public int getBuId() { return buId; } public void setBuId(int buId) { this.buId = buId; } public int getRoleId() { return roleId; } public void setRoleId(int roleId) { this.roleId = roleId; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public User(int id, String name, int age, int sex, int cityId, int buId, int roleId, String pinyinName) { super(); this.id = id; this.name = name; this.age = age; this.sex = sex; this.cityId = cityId; this.buId = buId; this.roleId = roleId; this.pinyinName = pinyinName; } }
在为它的属性赋值时,一般有两种方式,使用构造函数和使用set方法。但是使用构造函数有时会忘了各个字段的顺序 ,直接使用set方法,又比较麻烦。因此同事提出能够使用方法链,相似于StringBuilder的append方法ui
String s = new StringBuilder().append("0").append(1) .append(" 2 ").append(3).toString();
让bean的每一个属性的set方法都返回一个对象自己的引用,将User类的set方法改写成下面的样子:this
public User setId(int id) { this.id = id; return this; } public User setName(String name) { this.name = name; return this; } public User setAge(int age) { this.age = age; return this; } public User setSex(int sex) { this.sex = sex; return this; } public User setCityId(int cityId) { this.cityId = cityId; return this; } public User setBuId(int buId) { this.buId = buId; return this; } public User setRoleId(int roleId) { this.roleId = roleId; return this; } public User setPinyinName(String pinyinName) { this.pinyinName = pinyinName; return this; }
这样在对User的属性赋值时就简洁了许多。code
User user = new User().setId(1).setAge(18) .setBuId(127) .setRoleId(12) .setName("giraffe") .setCityId(12) .setSex(1) .setPinyinName("gif");
不过不知道这样写会不会有什么很差的地方~~对象