0

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?

priojewo
  • 937
  • 2
  • 11
  • 22
  • `resultSet.getMetaData()` returns a `ResultSetMetaData` object that describes the column types. – deanosaur Apr 07 '14 at 19:59
  • This is a perfect case for using dynamic programming... in Java it sucks, I would use Groovy for that. – Renato Apr 07 '14 at 20:10
  • The `ResultSetMetaData` is indeed one possibility but then I have to use a giant switch construct to check for all `java.sql.Types` and do the proper casting. This is annoying. So no possibility to do that in pure java at all? – priojewo Apr 07 '14 at 20:37

0 Answers0