循环javaBean属性

时间:2015-07-14 15:08:14

标签: java loops attributes iteration javabeans

我有一个java bean

public class Bean {

private Object field1;
private Object field2;

public Object getField1() {
    return field1;
}

public void setField1(Object field1) {
    this.field1 = field1;
}

public Object getField2() {
    return field2;
}

public void setField2(Object field2) {
    this.field2 = field2;
}
}

我想设置字段,所以我正在做这个硬编码

Bean c1 = new Bean();

c1.setField1(hmap.get(headers[1]));
c1.setField2(hmap.get(headers[2]));

我想用一个循环来做这个,因为我有17个字段。

for (count = 1; count < headers.length; count++) {
c1.setField1,2,3...("Parameter_" + count, messages.getString("field." + headers[count]));}

我该如何实现?使用JDK 16

1 个答案:

答案 0 :(得分:1)

使用Reflection,如下所示:

    Bean c1 = new Bean();

    c1.setField1("Object 1");
    c1.setField2("Object 2");

    for (int count = 1; count < headers.length; count++) 
    {
        //concatenate to get method name
        String methodName = "getField" + count;

        // using reflection, get collection of all methods in Bean class
        Method[] methods = Bean.class.getMethods();

        for(Method method : methods)
        {
            if (method.getName().equals(methodName))
            {
                // if it's the method you want, invoke it using 
                // the required params
                method.invoke("Parameter_" + count, messages.getString("field." + headers[count]));
            }
        }
    }