I need to retrieve the values from a ResultSet
to use them via reflexion to invoke a constructor.
I was trying with Class.cast(Object), but I always get an InvalidCastException
.
This is what I have:
Object[] args = new Object[count];
Class<?>[] arr = co.getParameterTypes();
for(i = 0; i<args.length; i++){
args[i] = arr[i].cast(rs.getObject(i+1));
}
Object t;
try {
t = co.newInstance(args);
} catch (Exception e) {
throw new RuntimeException(e);
}
return (T)t;
co is the constructor, and rs is the ResultSet
I already have.
Even if you can get this to work, there's a long-term maintenance nightmare that the order of the arguments in the Object's constructor may not match the order of the columns in the ResultSet
(the table in the RDB). e.g., if your Person
object has a constructor taking a firstName, lastName, the order of the columns in the DB Table may not match. It could be LAST_NAME, FIRST_NAME, or even FIRST_NAME, SOME_COLUMN_YOU_DONT_CARE_ABOUT, LAST_NAME.
In code I have seen to handle this issue more generically, they use reflection upon the domain object (e.g. Person) to get the property names (in my case, they looked at setters, not constructors, YMMV), then try to match them to the ResultSet
column names, using ResultSet.getMetaData()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With