/**
* @param args
*/
public static void main
(String[] args
) {
String sql
="select * from user where name=1";
try {
User user=BaseDao.getClass(sql, User.class);
System.
out.
println(user.
getName());
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 使用泛型类封装查询结果
* @param <T>
* @throws Exception
*/
public static <T
> T getClass
(String sql, Class
<T
> clazz
) throws Exception {
ps=con.prepareStatement(sql);
rs=ps.executeQuery();
//结果集的字段
//将字段添加到string数组
for(int i=0;i<md.getColumnCount();i++) {
mdString[i]=md.getColumnLabel(i+1);
}
//声明一个泛型类
T t=null;
//获得传入类的方法集合
Method[] methods
=clazz.
getMethods();
if(rs.next()) {
t=clazz.newInstance();
for(int j=0;j<mdString.length;j++) {
//将结果集的字段首字母替换成大写并且以set开头(例:setName对象类里面的set方法)
clsMethod="set"+clsMethod.replaceFirst(clsMethod.substring(0,1), clsMethod.substring(0, 1).toUpperCase());
//匹配传入类的方法集合如果匹配成功则执行。
if(clsMethod.equals(m.getName())) {
m.invoke(t, rs.getObject(j+1));
}
}
}
}
return t;
}
//源代码片段来自云代码http://yuncode.net