5

BeanUtils を使用して、次のような Java Bean と対話しようとしています。

public class Bean {
    private List<Integer> prices = new LinkedList<Integer>();

    public List<Integer> getPrices() {
        return prices;
    }
}

BeanUtils documentationによると、 BeanUtilsは次のインデックス付きプロパティをサポートしていますList

JavaBeans 仕様の拡張として、BeanUtils パッケージは、基礎となるデータ型が java.util.List (または List の実装) であるすべてのプロパティもインデックス付けされると見なします。

ただし、次のようなことをしようとするとします。

Bean bean = new Bean();

// Add nulls to make the list the correct size
bean.getPrices().add(null);
bean.getPrices().add(null);

BeanUtils.setProperty(bean, "prices[0]", 123);
PropertyUtils.setProperty(bean, "prices[1]", 456);

System.out.println("prices[0] = " + BeanUtils.getProperty(bean, "prices[0]"));
System.out.println("prices[1] = " + BeanUtils.getProperty(bean, "prices[1]"));

出力は次のとおりです。

prices[0] = null
prices[1] = 456

BeanUtils.setProperty()インデックス付きプロパティを設定できないのに、設定できないのはなぜPropertyUtils.setProperty()ですか? BeanUtils はLists 内のオブジェクトの型変換をサポートしていませんか?

4

1 に答える 1

5

BeanUtilsそれが機能するにはセッターメソッドが必要です。Beanクラスに のセッター メソッドがありませんprices。これを追加してコードを再実行すると、正常に動作するはずです:-

public void setPrices(List<Integer> prices) {
    this.prices = prices;
}
于 2011-01-28T02:33:41.073 に答える