I want to call the setter method of an object with a String
value which I receive from a resultSet
.
String value = resultSet.getString(id);
try {
Method setter = new PropertyDescriptor("field", obj.getClass()).getWriteMethod();
setMethod.invoke(obj, value);
}
...
This works perfectly when my object looks like this:
class Object {
private String field;
public void setField(String f) {
this.field = f;
}
}
Now I want this field value to be an integer:
class Object {
private int field;
public void setField(int f) {
this.field = f;
}
}
Now the code above throws an exception, because it can't find the method with String
as attribute. I can fix this when I modify my code to:
int value = resultSet.getInt(id);
How can I do this dynamically? Image I want to assign many fields by using this setter approach and I don't know what type the fields are in the object, I just want to call the appropriate setter method, which is declared in the object. My idea is to call the appropriate get... method on the resultSet by checking the type of the field in the object. But I don't know how to do this.
Any ideas?