Listに格納されたBeanの指定メンバを一括初期化するサンプル
BeanPropertyValueChangeClosureにメンバ名を指定して
CollectionUtils.forAllDoで実行するだけで
メンバを指定値で一括初期化することができるが初期化の条件を指定できないのが惜しい。
条件を指定できるメソッドが他にもあるのかな〜。
BeanPropertyValueChangeClosureは第三引数まで指定できるけど
例外時の動作指定っぽいので今回は第二引数まで。
材料は
org.apache.commons.beanutils
org.apache.commons.collections
org.apache.commons.lang
/** * * 実行。 * @throws Exception 例外 */ public void execute() throws Exception { final List<TestBean> list = new ArrayList<TestBean>(); while (list.size() < 10) { final int rand = RandomUtils.nextInt(4); if (rand == 1) { list.add(new TestBean()); } else { list.add(new TestBean(rand)); } } System.out.println("置換前"); for (final TestBean tb : list) { System.out.println(ToStringBuilder.reflectionToString( tb, ToStringStyle.SHORT_PREFIX_STYLE)); } final BeanPropertyValueChangeClosure beanPropertyValueChangeClosure = new BeanPropertyValueChangeClosure("hoge", 9); CollectionUtils.forAllDo(list, beanPropertyValueChangeClosure); System.out.println("置換後"); for (final TestBean tb : list) { System.out.println(ToStringBuilder.reflectionToString( tb, ToStringStyle.SHORT_PREFIX_STYLE)); } } /** * * <HR> * <P> * ■モジュール名 <BR> * <BLOCKQUOTE> * Test.java <BR> * </BLOCKQUOTE> * <P> * ■クラス仕様 <BR> * <BLOCKQUOTE> * TestクラスはBeenクラスです。<BR> * </BLOCKQUOTE> * <P> * <HR> * <P> */ public class TestBean { /** * 確認用数値 */ private Integer hoge; /** * * コンストラクタ * @param hoge 確認用数値 */ public TestBean(final int hoge) { this.hoge = Integer.valueOf(hoge); } /** * * コンストラクタ */ public TestBean() { } /** * * 確認用数値の取得 * @return 確認用数値 */ public int getHoge() { return hoge; } /** * * 確認用数値の設定 * @param hoge 確認用数値 */ public void setHoge(final int hoge) { this.hoge = hoge; } }