转自:http://hi.baidu.com/webidea/blog/item/d269a9d313bbf3dca8ec9a28.html
Spring中的BeanUtils类为java中的JavaBean类提供了一此常用的静态方法.通过这些方法可以方便地使用在Web应用程序中.如在对象与对象之间属性的复制工作.
上面介绍的为BeanUtils类提供的属性复制功能:
public class BeanUtilsDemo {
private String firstName;
private String lastName;
protected static Log log = LogFactory.getLog(BeanUtilsDemo.class);
public BeanUtilsDemo() {
}
public BeanUtilsDemo(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public static void main(String args[]) {
BeanUtilsDemo bean1 = new BeanUtilsDemo("谷", "键");
BeanUtilsDemo bean2 = new BeanUtilsDemo("陈", "澣");
log.info(bean1.toString());
log.info(bean2.toString());
BeanUtils.copyProperties(bean1, bean2);
log.info(bean1.toString());
log.info(bean2.toString());
//下面几行为通过instantiateClass方法的构造器来创建对象
Constructor cons;
Class className = Class
.forName("com.inqgen.spring.beanutils.BeanUtilsDemo");
cons = className.getConstructor(String.class, String.class);
BeanUtilsDemo bean3 = (BeanUtilsDemo) BeanUtils.instantiateClass(
cons, new Object[] { "张", "黄莺" });
log.info(bean3);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String toString() {
return "[" + getFirstName() + "," + getLastName()+ "]";
}
最后在console中的结果为:
[谷,键],[陈,澣],[谷,键],[谷,键]
beans:将输出为:[张,黄莺]
从结果中可以看到原对象bean1中的属性值被复工制到了bean2中.