Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a List indexed property with BeanUtils

I'm attempting to use BeanUtils to interact with a Java bean similar to the following:

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

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

According to the BeanUtils documentation, BeanUtils does support indexed properties that are Lists:

As an extension to the JavaBeans specification, the BeanUtils package considers any property whose underlying data type is java.util.List (or an implementation of List) to be indexed as well.

However, let's say I try to do something like the following:

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]"));

The output is:

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

Why is BeanUtils.setProperty() unable to set the indexed property, while PropertyUtils.setProperty() can? Does BeanUtils not support type conversion for objects inside Lists?

like image 608
Charles Hellstrom Avatar asked Jan 27 '11 20:01

Charles Hellstrom


1 Answers

BeanUtils requires a setter method for it to work. Your Bean class is missing the setter method for prices, add this and rerun your code, it should work fine:-

public void setPrices(List<Integer> prices) {
    this.prices = prices;
}
like image 178
limc Avatar answered Sep 28 '22 03:09

limc