使用BeanUtils设置List索引属性

Cha*_*rom 3 java javabeans apache-commons-beanutils

我正在尝试使用BeanUtils与类似于以下内容的Java bean进行交互:

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

    public List<Integer> getPrices() {
        return prices;
    }
}
Run Code Online (Sandbox Code Playgroud)

根据BeanUtils文档,BeanUtils支持Lists的索引属性:

作为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]"));
Run Code Online (Sandbox Code Playgroud)

输出是:

prices[0] = null
prices[1] = 456
Run Code Online (Sandbox Code Playgroud)

为什么BeanUtils.setProperty()无法设置索引属性,PropertyUtils.setProperty()可以吗?BeanUtils不支持Lists中对象的类型转换吗?

lim*_*imc 5

BeanUtils需要一个setter方法才能工作.你的Bean类缺少setter方法prices,添加它并重新运行你的代码,它应该工作正常: -

public void setPrices(List<Integer> prices) {
    this.prices = prices;
}
Run Code Online (Sandbox Code Playgroud)