/**
* apache的Beanutils简单使用
*
* @author 张明学
*
*/
public class BeanUtilsStudy {
public static void main(String[] args) throws Exception {
PersonBean pbean = new PersonBean("java", 12);
pbean.setP("P属性");
// 定义几个属性名称
String propertyP = "p";
String propertyName = "name";
String propertyAge = "age";
Object returnValue = null;
// **************getProperty与setProperty方法:获取与设置JavaBean的属性**************
// 获取p属性值
returnValue = BeanUtils.getProperty(pbean, propertyP);
System.out.println(returnValue);
// 获取name属性值
returnValue = BeanUtils.getProperty(pbean, propertyName);
System.out.println(returnValue);
// 设置p属性值
BeanUtils.setProperty(pbean, propertyP, "C++");
System.out.println(pbean.getP());
// 设置age属性值
BeanUtils.setProperty(pbean, propertyAge, 24);
System.out.println(pbean.getAge());
// 可以自动帮我们进行类型转换
BeanUtils.setProperty(pbean, propertyAge, "25");
System.out.println(pbean.getAge());
// birthday类型的java.util.Date类,下面这样写在它在定义的是必须要实例化birthday
// java.util.Date有一个setTime()方法可以看作JavaBean
BeanUtils.setProperty(pbean, "birthday.time", new Date().getTime());
System.out.println(pbean.getBirthday());
// **************copyProperties方法:将一个JavaBean的属性copy到另一个JavaBean中**************
// PersonBean2是PersonBean的子类
PersonBean2 pb2 = new PersonBean2();
// 将pbean的属性值copy到pb2属性
BeanUtils.copyProperties(pb2, pbean);
System.out.println(pb2.getName());
// **************describe方法:将javaBean转换成Map对象************** \\
Map beanMap = BeanUtils.describe(pbean);
for (Object key : beanMap.keySet()) {
System.out.println(key + "=" + beanMap.get(key));
}
// **************populate方法:将Map中的值设置到javaBean对象************** \\
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", ".NET");
map.put("age", 32);
map.put("p", "PPP");
BeanUtils.populate(pbean, map);
System.out.println(pbean.getName() + "\t" + pbean.getAge() + "\t"
+ pbean.getP());
// 还有一个PropertyUtils
returnValue = PropertyUtils.getProperty(pbean, propertyName);
System.out.println(returnValue);
PropertyUtils.setProperty(pbean, propertyAge, 21);
System.out.println(pbean.getAge());
// PropertyUtils.setProperty(pbean, propertyAge, "21");不能自动进行类型转换
}
}
其中用的JavaBean如下:
public class PersonBean {
private String name;
private int age;
private Date birthday = new Date();
private String x;
public PersonBean() {
}
public PersonBean(String name, int age) {
this.name = name;
this.age = age;
}
public String getP() {
return x;
}
public void setP(String p) {
this.x = p;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class PersonBean2 extends PersonBean {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}