I have a class called Bean which has 3 fields
public class Bean {
private Object field0;
private Object field1;
private Object field2;
public Object getField0() {
return field0;
}
public void setField0(Object field0) {
this.field0 = field0;
}
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;
}
I want to set each one of the fields with data to do so
int j, i;
for (j = 0; j < body.size(); j++) {
line = new Bean();
List row = body.get(j);
HashMap map = new HashMap(headers.length);
for (i = 0; i < headers.length; i++) {
line.choosefield2(i, headers, row);
}
list.add(line);
}
and choosefield2 is in the bean:
public void choosefield2(int i, String[] headers, List row) {
switch (i) {
case 0:
this.setField0(row.get(0));
break;
case 1:
this.setField1(row.get(1));
break;
case 2:
this.setField2(row.get(2));
break;
Can I do this in a for cycle instead of doing a case switch? I have way more than 3 fields so it's not really practical. I heard reflections might be an option. I wanted something like
for (i = 0; i < headers.length; i++) {
line.setField[i]=row.get(i);
}
list.add(line);
}
is this possible? Using JDK 1.6
Aucun commentaire:
Enregistrer un commentaire