日期:2014-05-20 浏览次数:20992 次
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 java.sql.Statement;
import jdbc.util.JDBCUtils;
public class ResultMetaDataDemo
{
public Object getStudent(String sql, Class claz) throws SQLException,
InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException
{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
conn = JDBCUtils.getConnect();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
// 列数
int columCount = rsmd.getColumnCount();
// 列名
String[] columNames = new String[columCount];
for (int i = 0; i < columNames.length; i++)
{
columNames[i] = rsmd.getColumnName(i + 1);
}
Object obj = null;
Method[] methods = claz.getMethods();
if (rs.next())
{
// 创建对象
obj = claz.newInstance();
for (int i = 0; i < columNames.length; i++)
{
// 列名
String columName = columNames[i];
// 拼接方法名
String methodName = "set" + columName.substring(0, 1)
+ columName.substring(1).toLowerCase();
for (Method method : methods)
{
if (method.getName().equals(methodName))
{
//进行反射调用方法设置值的时候,形参和实参不匹配!
//从Oracle数据库中取出来的整数类型是java.math.BigDecimal,日期类型是java.sql.Date,
//我期望的是java.lang.Integer和java.util.Date,求解?
method.invoke(obj, new Object[]
{ rs.getObject(columName)});
}
}
}
}
return obj;
}
finally
{
try
{
JDBCUtils.free(conn, ps, rs);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
/**
* 抛出的异常:
* Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at jdbc.oper.ResultMetaDataDemo.getStudent(ResultMetaDataDemo.java:68)
at main.ServerDemo.main(ServerDemo.java:36)
问题:请各位看看哪边有错,提供一下解决方案,谢谢各位!
*/
}