BeanUtils 提供了对于JavaBean进行各种操作, 比如对象,属性复制等等。
1.创建一个实体类
class="java">
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.运行结果
- 大小: 10.4 KB