Java如何设置bean的索引属性值?
在此示例中,我们显示如何设置索引属性的值。在下面的代码中,我们修改了数组类型的值。我们要改变的第二颜色MyBean的colors属性。
我们以与使用该PropertyUtils.setSimpleProperty方法相同的方式进行操作。对于索引属性,我们使用该PropertyUtils.setIndexedProperty方法并传递四个参数,它们是要操作的bean的实例,索引属性名称,要更改的索引以及最后一个新值。
package org.nhooo.example.commons.beanutils;
import org.apache.commons.beanutils.PropertyUtils;
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.nhooo.example.commons.beanutils;
public class MyBean {
private String[] colors;
public void setColors(String[] colors) {
this.colors = colors;
}
public String[] getColors() {
return colors;
}
}此代码的输出是:
Colors = [red, green, blue] Colors = [red, orange, blue]
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=commons-beanutils/commons-beanutils/1.9.3/commons-beanutils-1.9.3.jar -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>