BeanUtils工具类
封装JavaBean(标准的Java类)
注意:
- 类必须被public修饰
- 必须提供空参的构造器
- 成员变量必须使用private修饰
- 提供公共的setter和getter方法
类中的属性:setter和getter方法截取后的产物
例如:getUsername() —->Username—–>username
代码理解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54//UserTest类
public class UserTest {
public String getHehe() {
return gender;
}
public void setHehe(String gender) {
this.gender = gender;
}
public String toString() {
return "UserTest{" +
"gender='" + gender + '\'' +
'}';
}
private String gender;
}
//测试
public class BeanUtilsTest {
public void test(){
UserTest user = new UserTest();
try {
BeanUtils.setProperty(user,"hehe","hxx");
System.out.println(user);
String hehe = BeanUtils.getProperty(user, "hehe");
System.out.println(hehe);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
public class BeanUtilsTest {
public void test(){
UserTest user = new UserTest();
try {
//这里传的是根据setHehe和getHehe方法得到的hehe,进而给gender赋值
BeanUtils.setProperty(user,"hehe","hxx");
System.out.println(user);
String hehe = BeanUtils.getProperty(user, "hehe");
System.out.println(hehe);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
方法
- setProperty(属性名,属性值)
- getProperty(属性名,属性值)
- populate(Object obj,Map map):将map集合的键值对信息,封装到对应的JavaBean对象