循环 javaBean 属性
Looping javaBean attributes
我有一个java豆子
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
使用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]));
}
}
}
我有一个java豆子
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
使用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]));
}
}
}