時には、Javaクラスから他のクラスへのコピープロパティが必要な場合もありますが、これを手動または独自のリフレクション実装で行うことができますが、この場合は、Apacheのユーティリティを使用してリフレクションを自動化します
-
JDK 1.6
2.手をつないで
-
eclipseで “Java Project”を作成します.
-
プロジェクト名:CopyPropertiesをクリックし、「完了」ボタンをクリックします.
-
common-beanutils-xxx.zip`と
commons-logging-xxx.zip`の両方を解凍してください. -
commons-beanutils-xxx.jar`と
commons-logging-xxx.jar`をファイルに追加してください.
プロジェクトのクラスパス。
パッケージ `pojo.from`に新しいPerson” 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.テスト
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 ** ** ** 人15人othePerson 0 null ** ** ** After BeanUtils.copyProperties ** ** ** Person 15 rene othePerson 15 rene
ソースコードをダウンロードする
ダウンロードする – リンク://wp-content/uploads/2012/07/CopyProperties.zip[CopyProperties.zip](6 KB)
参考文献
-
http://commons.apache.org/beanutils/
[commons-beanutils official
ウェブサイト]。
commons-logging official website
java
properties
リンク://タグ/反射/[反射]