1. 程式人生 > >java反射機制set方法 連線資料庫(還有待修改,沒有迴圈ResultSet物件)

java反射機制set方法 連線資料庫(還有待修改,沒有迴圈ResultSet物件)

public ArrayList query() {
String methodname;
ArrayList list=new ArrayList();
try {
con=db.getCon();
ps=con.prepareStatement(this.getQuery());
for(int i=0;i<this.getFiled().length-1;i++){
//System.out.println("列"+this.getFiled()[i].getName());
//System.out.println("方法名:"+methodname);
if(this.getFiled()[i].getGenericType().toString().equals("int")){
methodname="set"+this.getFiled()[i].getName().substring(0,1).toUpperCase()+this.getFiled()[i].getName().substring(1,this.getFiled()[i].getName().length())
+"("+rs.getInt(this.getFiled()[i].getName())+")";
}else{
// System.out.print("字元");
methodname="set"+this.getFiled()[i].getName().substring(0,1).toUpperCase()+this.getFiled()[i].getName().substring(1,this.getFiled()[i].getName().length())
+"("+rs.getString(this.getFiled()[i].getName())+")";

}
Method me= this.getBean().getClass().getDeclaredMethod(methodname,new Class[]{});
me.invoke(this.getBean(),new Object[]{});

//System.out.print(this.getFiled()[i].getGenericType());
list.add(this.getBean());
}
// System.out.print("list大小"+list.size());
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
這是我寫的通用程式碼,執行查詢方法,獲得查詢語句如下
public String getQuery() {
if(this.getId()>0){
this.setQuery("select * from "+this.getTablename());
}else if(this.colname!=null){
String colvalue=null;
for(int i=0;i<this.invokeGet().size()-1;i++){
if(this.getFiled()[i+1].getName().toLowerCase().equals(this.colname.toLowerCase())){
colvalue=this.invokeGet().get(i).toString();
}
}
this.setQuery("select * from "+this.getTablename()+" where "+this.colname+"='"+colvalue+"'");
}
else{
this.setQuery("select * from "+this.getTablename());
}
return query;
}

上述語句獲得查詢語句肯定是沒有問題,問題出現在給methodname賦値,也就是set方法的名稱獲得就出錯,執行也有疑問,我執行get方法的時候不需要帶()只需要方法名,可是用set方法,必須得要括號,因為要把rs包含起來,怎麼辦?