How do I set indexed property value of a bean?

In this example we show how to set the value of an indexed property. In the code below we modified the value of an array type. We’ll change the second colors of MyBean‘s colors property.

We do it in the same way as we are using the PropertyUtils.setSimpleProperty method. For indexed property we use the PropertyUtils.setIndexedProperty method and passes four arguments, they are the instance of bean to be manipulated, the indexed property name, the index to be changes and finally the new value.

package org.kodejava.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.MyBean;

import java.util.Arrays;

public class PropertySetIndexedExample {
    public static void main(String[] args) {
        String[] colors = new String[]{"red", "green", "blue"};

        MyBean myBean = new MyBean();
        myBean.setColors(colors);
        System.out.println("Colors = " + Arrays.toString(myBean.getColors()));

        try {
            PropertyUtils.setIndexedProperty(myBean, "colors", 1, "orange");
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Colors = " + Arrays.toString(myBean.getColors()));
    }
}
package org.kodejava.commons.beanutils.support;

public class MyBean {
    private String[] colors;

    public void setColors(String[] colors) {
        this.colors = colors;
    }

    public String[] getColors() {
        return colors;
    }
}

The output of this code is:

Colors = [red, green, blue]
Colors = [red, orange, blue]

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.