java - Looping javaBean atributes -
i have 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; } }
i want set fields i'm doing hardcoded
bean c1 = new bean(); c1.setfield1(hmap.get(headers[1])); c1.setfield2(hmap.get(headers[2]));
i cycle because have 17 fields.
for (count = 1; count < headers.length; count++) { c1.setfield1,2,3...("parameter_" + count, messages.getstring("field." + headers[count]));}
how can implement this? using jdk 16
using reflection, follows:
bean c1 = new bean(); c1.setfield1("object 1"); c1.setfield2("object 2"); (int count = 1; count < headers.length; count++) { //concatenate method name string methodname = "getfield" + count; // using reflection, collection of methods in bean class method[] methods = bean.class.getmethods(); for(method method : methods) { if (method.getname().equals(methodname)) { // if it's method want, invoke using // required params method.invoke("parameter_" + count, messages.getstring("field." + headers[count])); } } }
Comments
Post a Comment