JAVA 利用反射机制查询数据库返回相应对象
jopen
10年前
public static void main(String [] rags){ SQLHepler SH=new SQLHepler(); String sql="select * from DB_Image"; String [] p={"107"}; try { List<Object> c=SH.excuteSelectSQL(sql, null, DBImage.class); for (Object o:c) { DBImage cam=(DBImage) o; System.out.println(cam.getImageID()+" "+cam.getImageRealPath()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private List<String> getAllMethods(Class c){ List<String> allMendth=new ArrayList<String>(); Field [] f=c.getDeclaredFields(); for(int i=0;i<f.length;i++){ String m="set"; m+=f[i].getName(); allMendth.add(m); } return allMendth; } public List<Object> excuteSelectSQL(String sql,String [] parmates,Class clazz) throws Exception{ List<Object> all=new ArrayList<Object>(); Conn conn=new Conn(); this.con=conn.getConn(); this.ps=con.prepareStatement(sql); if(parmates!=null && !parmates.equals("")){ int index=1; for(String s:parmates){ this.ps.setString(index, s); index++; } } this.rs=this.ps.executeQuery(); while(rs.next()){ Object o = clazz.newInstance(); List<String> allMethods=getAllMethods(clazz); int index=1; for(String s:allMethods){ clazz.getDeclaredMethod(s, String.class).invoke(o, rs.getString(index)); index++; } all.add(o); } return all; }