Как использовать отражение для копирования свойств из Pojo в другие Java Beans
Иногда нам нужно скопировать свойства из класса Java в другой, мы можем сделать это вручную или с нашей собственной реализацией рефлексии, но в этом случае мы используем рефлексию для автоматизации с помощью утилиты apache
Требования
-
commons-beanutils, вы можете скачать здесьhttp://commons.apache.org/beanutils/
-
commons-loging, вы можете скачать отсюдаhttp://commons.apache.org/logging/
-
Затмение
-
JDK 1.6
2. Руки вверх
-
Создайте «Java-проект» в Eclipse.
-
Название проекта: CopyProperties и нажмите кнопку «Готово».
-
Разархивируйте
common-beanutils-xxx.zip
иcommons-logging-xxx.zip
. -
Добавьте
commons-beanutils-xxx.jar
иcommons-logging-xxx.jar
в путь к классам вашего проекта.
Создайте новый класс «Человек» в пакетеpojo.from
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; } }
Создайте класс «OthePerson» в пакетеpojo.to
с такими же полями
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. тестирование
Создайте тестовый класс в пакетеpojo.test
с помощью метода main и проверьте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 КБ)