JDBC泛型類反射封裝結果集

wtsoftware發表於2012-09-09
// 在此輸入java程式碼
 * @[author]param[/author] 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());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
   
}  
       /**
 * 使用泛型類封裝查詢結果
 * @[author]param[/author] <T>
 * @throws Exception
 */
public static <T> T getClass(String sql, Class<T> clazz) throws Exception {
    PreparedStatement ps = null;
    ResultSet rs = null;
    Connection con=JDBCUtil.getConnection();
    ps=con.prepareStatement(sql);
    rs=ps.executeQuery();
    //結果集的欄位
    ResultSetMetaData md=rs.getMetaData();
    //將欄位新增到string陣列
    String[] mdString=new String[md.getColumnCount()];
    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++) {
            String clsMethod=mdString[j];
            //將結果集的欄位首字母替換成大寫並且以set開頭(例:setName物件類裡面的set方法)
            clsMethod="set"+clsMethod.replaceFirst(clsMethod.substring(0,1), clsMethod.substring(0, 1).toUpperCase());
            for(Method m:methods) {
                //匹配傳入類的方法集合如果匹配成功則執行。
                if(clsMethod.equals(m.getName())) {
                    m.invoke(t, rs.getObject(j+1));
                }
            }
        }
    }
    return t;
}
<p class="indent">

[該貼被wtsoftware於2012-09-09 17:07修改過]

[該貼被wtsoftware於2012-09-09 17:32修改過]

相關文章