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
.
我需要从ResultSet中检索值,以通过reflexion使用它们来调用构造函数。我正在尝试使用Class.cast(Object),但我总是得到一个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.
co是构造函数,rs是我已经拥有的ResultSet。
1 个解决方案
#1
1
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.
即使你可以让它工作,也存在一个长期的维护噩梦,即Object的构造函数中的参数顺序可能与ResultSet中的列的顺序(RDB中的表)不匹配。例如,如果您的Person对象具有采用firstName,lastName的构造函数,则DB表中列的顺序可能不匹配。它可能是LAST_NAME,FIRST_NAME,甚至是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()
.
在代码中,我已经看到更一般地处理这个问题,他们使用对域对象(例如Person)的反射来获取属性名称(在我的例子中,他们查看了setter,而不是构造函数,YMMV),然后尝试将它们匹配到ResultSet列名,使用ResultSet.getMetaData()。
#1
1
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.
即使你可以让它工作,也存在一个长期的维护噩梦,即Object的构造函数中的参数顺序可能与ResultSet中的列的顺序(RDB中的表)不匹配。例如,如果您的Person对象具有采用firstName,lastName的构造函数,则DB表中列的顺序可能不匹配。它可能是LAST_NAME,FIRST_NAME,甚至是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()
.
在代码中,我已经看到更一般地处理这个问题,他们使用对域对象(例如Person)的反射来获取属性名称(在我的例子中,他们查看了setter,而不是构造函数,YMMV),然后尝试将它们匹配到ResultSet列名,使用ResultSet.getMetaData()。