将学习成果分享给大家。
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import com.itcast.jdbc.domain.User;
//JDBC_利用Java反射技术将查询结果封装为对象
public class CRMTest
{
public static void main(String[] args) throws Exception
{
//另外一种解决方法名为题为
//sql = "select id as Id,name as Name,birthday as Birthday,money as Money from user where id = 3"
String sql = "select * from user where id = 3";
//类必须有空的构造函数
User user = (User) getObject(sql,User.class);
System.out.println(user);
}
public static Object getObject(String sql, Class clazz) throws Exception
{
{
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
try
{
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData rsmt = rs.getMetaData();
int count = rsmt.getColumnCount();
String[] colNames = new String[count];
// 数据库的列数除了主键id,从列下标1开始
for (int i = 1; i <= count; i++)
{
// System.out.print(rsmt.getColumnClassName(i)+"\t");
// System.out.print(rsmt.getColumnName(i)+"\t");
// System.out.println(rsmt.getColumnLabel(i)); 列的别名
// 为了防止出现列别名引起列不全,采用Lable
colNames[i - 1] = rsmt.getColumnLabel(i);
}
Object object = null;
Method ms[] = clazz.getMethods();
if (rs.next())
{
object = clazz.newInstance();//实例化对象
for (int i = 0; i < colNames.length; i++)
{
String colName = colNames[i];
String methodName = "set" + colName;
for (Method m : ms)
{
//为了解决methodName与设置属性的方法名一致
if (methodName.equals(m.getName().toLowerCase()))
{
//反射,将实例对象,和方法名注入方法域中
m.invoke(object, rs.getObject(colName));
}
}
}
}
return object;
} finally
{
JdbcUtils.free(rs, ps, conn);
}
}
}
}