java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to set indexed property value of a bean?

In this example we display 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 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 the finally the new value.

package com.javacoderanch.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

import java.util.Arrays;
import java.lang.reflect.InvocationTargetException;

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 (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        System.out.println("Colors = " + Arrays.toString(myBean.getColors()));
    }
}