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>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024