黑马程序员技术交流社区
标题:
一个类型转换问题
[打印本页]
作者:
陈建华
时间:
2012-12-5 16:10
标题:
一个类型转换问题
下面的m.invoke(user, rs.getObject(colName));
方法为什么当遇见int类型时出现类型匹配异常。
package cn.itcast.jdbc;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import com.itcast.domain.User;
public class ORMTest {
/**
* @param args
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws SQLException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws Exception {
User user = getUser("select * from user where name='wangwu'");
System.out.println(user.getName());
System.out.println(user.getId());
System.out.println(user.getMoney());
System.out.println(user.getBirthday());
}
static User getUser(String sql) throws Exception{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
String[] colNames = new String[count];
for(int i=1; i<=count; i++){
colNames[i-1] = rsmd.getColumnName(i);
}
User user = null;
if(rs.next()){
user = new User();
for(int i=0; i<colNames.length; i++){
String colName = colNames[i];
String methodColName = colName.substring(0, 1).toUpperCase()+colName.substring(1);
String methodName = "set"+methodColName;
Method[] ms = user.getClass().getMethods();
for(Method m: ms){
if(methodName.equals(m.getName())){
if("setId".equals(methodName)){
m.invoke(user, rs.getInt(colName));
}else{
m.invoke(user, rs.getObject(colName));
}
// m.invoke(user, rs.getObject(colName));
}
}
}
}
return user;
}finally{
JdbcUtils.prepareClose(rs, ps, conn);
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2