概述:一个可以简化封装数据时繁琐操作的工具类
使用:
- 加载jar包(本文使用maven)在pom文件中加入
1
2
3
4
5<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency> - 定义一个标准类(这里使用了Lombok)
1
2
3
4
5
6
7
8
9
10
11
12
13import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@ToString
public class User {
@Getter@Setter
private int id;
@Getter@Setter
private String username;
@Getter@Setter
private String password;
}用法
- 使用populate将map中数据封装到JavaBean中
1
2
3
4
5public void function() throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
User user = new User();
Map<String,String> map = new HashMap<>();
BeanUtils.populate(user,map);
}/*注意key的值要一致*/ - 使用setproperty为JavaBean对象赋值
1
2
3
4
5public void function() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Object bean = Class.forName("itcast.domain.User").getDeclaredConstructor().newInstance();
BeanUtils.setProperty(bean,"username","张三");
BeanUtils.setProperty(bean,"password","123456");
} - 使用getproperty来获取JavaBean对象的键值
1
2
3
4
5
6
7public void function() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Object bean = Class.forName("itcast.domain.User").getDeclaredConstructor().newInstance();
String username = BeanUtils.getProperty(bean, "username");
String password = BeanUtils.getProperty(bean, "password");
BeanUtils.setProperty(bean,"username","张三");
BeanUtils.setProperty(bean,"password","123456");
} - 将bean中的值放入Map中
1
2
3
4public void function()throws Exception{
Object bean = Class.forName("itcast.domain.User").getDeclaredConstructor().newInstance();
Map<String, String> map = BeanUtils.describe(bean);
} - 两个JavaBean对象之间的赋值本文只列举了常用的几种用法,其他内容详见官方API文档
1
2
3
4
5
6
7
8public void function()throws Exception{
User user1 = new User();
user1.setPassword("123456");
user1.setUsername("张三");
User user2 = new User();
BeanUtils.copyProperties(user2,user1);
System.out.println(user2.toString());
}