最近在学习网站开发,在后端获取网站请求数据的时候用到了BeanUtils.populate()方法,具体用法是:
BeanUtils.populate(object obj, Map<String, String[]> map);
于是我就在想这个方法是怎么把map中的数据封装到obj对象里的。打开源码看,看别人写的代码是真难受,看了半天还是没看懂。上网搜了一下,发现多数都是在讲用法,关于方法的实现过程一部分人是说obj对象里要有名称与map中key对应的成员变量,另一部分说是要有与key对应的set方法,讲得都不太明白。
自己动手,丰衣足食。写几个类测试下,上代码。先构建4个Student对象:
StudentA.java
/*
* 有r成员,方法各自对应
*/
public class StudentA {
private String name;
private String number;
private String sex;
private String r_name;
private String r_number;
private String r_sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getR_name() {
return r_name;
}
public void setR_name(String r_name) {
this.r_name = r_name;
}
public String getR_number() {
return r_number;
}
public void setR_number(String r_number) {
this.r_number = r_number;
}
public String getR_sex() {
return r_sex;
}
public void setR_sex(String r_sex) {
this.r_sex = r_sex;
}
public StudentA() {
super();
}
public StudentA(String name, String number, String sex) {
super();
this.name = name;
this.number = number;
this.sex = sex;
}
}
StudentB.java
/*
* 有r成员,但r方法对应到不带r成员上
*/
public class StudentB {
private String name;
private String number;
private String sex;
private String r_name;
private String r_number;
private String r_sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}