apache commons工具类之 BeanUtils
2016-07-15 16:02
267 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/iteye_7059/article/details/82654659
BeanUtils 提供了对于JavaBean进行各种操作, 比如对象,属性复制等等。
1.创建一个实体类
2.创建一个测试类
3.运行结果
1.创建一个实体类
package commons;
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2.创建一个测试类
package commons;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
public class TestUser {
public static void main(String[] args){
//创建一个user对象,用来作为被克隆的对象
User user = new User();
user.setName("csc");
user.setAge(24);
try {
//1.克隆
User user2 = (User) BeanUtils.cloneBean(user);
System.out.println(user2.getName()+" >>> "+ user2.getAge());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
Map<String,Object> map = new HashMap<String,Object>();
map.put("name", "csc1");
map.put("age", 27);
User u = new User();
try {
//2.将一个Map对象转化为一个Bean
//这个Map对象的key必须与Bean的属性相对应
BeanUtils.populate(u, map);
System.out.println(u.getName()+" >>> "+ u.getAge());
//3.将一个Bean转化为一个Map对象
Map<String,String> mapbean = BeanUtils.describe(u);
for (Map.Entry<String, String> entry : mapbean.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//key= class and value= class commons.User 再次转化没问题。
User us = new User();
BeanUtils.populate(us, mapbean);
System.out.println(us.getName()+" >>> "+ us.getAge());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
3.运行结果
相关文章推荐
- Apache Commons 常用工具类整理
- Java工具类之Apache的Commons Lang和BeanUtils
- Java工具类之Apache的BeanUtils
- apache commons工具类简介
- 使用BeanUtils工具类操作Java bean
- Apache Commons--RandomStringUtils随机数工具类
- Java工具类之Apache的Commons Lang和BeanUtils
- Apache Commons 工具类介绍及简单使用
- Apache Commons BeanUtils包学习(1)-BeanUtils.copyProperties
- Spring中的BeanUtils与apache commons中的BeanUtils用法[1]
- Apache Commons 工具类介绍及简单使用
- Apache Commons 工具类介绍及简单使用
- Apache Commons 工具类介绍及简单使用
- apache commons工具类简介
- Java工具类之Apache的Commons Lang和BeanUtils
- Apache Commons开源的工具类的介绍
- beanutils工具类将字符串转换成Date(java.util.Date)数据类型的方法
- apache commons工具类简介
- Apache Commons 工具类介绍及简单使用
- Apache Commons 工具类介绍及简单使用