有时我们需要将属性从Java类复制到其他类,我们可以手动执行此操作,也可以使用自己的反射实现,但在这种情况下,请使用apache的实用工具将反射自动执行
要求
- commons-beanutils,您可以从这里下载http://commons.apache.org/beanutils/
- commons-loging,您可以从此处下载http://commons.apache.org/logging/
- 日食
- JDK 1.6
2.动手
- 在eclipse中创建一个“ Java项目”。
- 项目名称:CopyProperties,然后单击“完成”按钮。
- 解压缩
common-beanutils-xxx.zip
和commons-logging-xxx.zip
。 - 将
commons-beanutils-xxx.jar
和commons-logging-xxx.jar
到项目的类路径。
在包pojo.from
创建一个新的类“ Person”。
package pojo.from;
public class Person {
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;
}
}
在pojo.to
创建具有相同字段的类“ OthePerson”
package pojo.to;
public class OthePerson {
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;
}
}
3.测试
使用main方法在pojo.test
包中创建一个测试类,并测试commons-beanutils
。
package pojo.test;
import org.apache.commons.beanutils.BeanUtils;
import pojo.from.Person;
import pojo.to.OthePerson;
/**
* Class for test copy properties
*
* @author Rene Enriquez
* @date 23/07/2012
*
*/
public class Test {
/**
* Main method
*
* @param args
*/
public static void main(String[] args) throws Exception {
Person person = new Person();
person.setAge(15);
person.setName("rene");
OtherPerson othePerson = new OtherPerson();
System.out.println("*** Before BeanUtils.copyProperties ***");
System.out.println("Person");
System.out.println(person.getAge());
System.out.println(person.getName());
System.out.println("othePerson");
System.out.println(othePerson.getAge());
System.out.println(othePerson.getName());
//copy properties from (target, source)
BeanUtils.copyProperties(othePerson, person);
System.out.println("\n*** After BeanUtils.copyProperties ***");
System.out.println("Person");
System.out.println(person.getAge());
System.out.println(person.getName());
System.out.println("othePerson");
System.out.println(othePerson.getAge());
System.out.println(othePerson.getName());
}
}
输出量
*** Before BeanUtils.copyProperties ***
Person
15
rene
othePerson
0
null
*** After BeanUtils.copyProperties ***
Person
15
rene
othePerson
15
rene
下载源代码
下载它– CopyProperties.zip (6 KB)
参考文献
翻译自: https://mkyong.com/java/how-to-use-reflection-to-copy-properties-from-pojo-to-other-java-beans/