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
<!-- https://search.maven.org/remotecontent?filepath=commons-beanutils/commons-beanutils/1.9.4/commons-beanutils-1.9.4.jar -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
Latest posts by Wayan (see all)
- How do I convert Map to JSON and vice versa using Jackson? - June 12, 2022
- How do I find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022