リフレクションを使用してPojoから他のJava Beanにプロパティをコピーする方法
Javaクラスから他のクラスにプロパティをコピーする必要がある場合があります。これを手動または独自のリフレクション実装で行うことができますが、この場合、Apacheのユーティリティでリフレクションを使用して自動化します。
必要条件
-
commons-beanutils、ここからダウンロードできますhttp://commons.apache.org/beanutils/
-
commons-logging、ここからダウンロードできます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)