JAVA 利用反射机制查询数据库返回相应对象

傷城~ 2022-08-25 11:53 221阅读 0赞
  1. public static void main(String [] rags){
  2. SQLHepler SH=new SQLHepler();
  3. String sql="select * from DB_Image";
  4. String [] p={"107"};
  5. try {
  6. List<Object> c=SH.excuteSelectSQL(sql, null, DBImage.class);
  7. for (Object o:c) {
  8. DBImage cam=(DBImage) o;
  9. System.out.println(cam.getImageID()+" "+cam.getImageRealPath());
  10. }
  11. } catch (Exception e) {
  12. // TODO Auto-generated catch block
  13. e.printStackTrace();
  14. }
  15. }
  16. private List<String> getAllMethods(Class c){
  17. List<String> allMendth=new ArrayList<String>();
  18. Field [] f=c.getDeclaredFields();
  19. for(int i=0;i<f.length;i++){
  20. String m="set";
  21. m+=f[i].getName();
  22. allMendth.add(m);
  23. }
  24. return allMendth;
  25. }
  26. public List<Object> excuteSelectSQL(String sql,String [] parmates,Class clazz) throws Exception{
  27. List<Object> all=new ArrayList<Object>();
  28. Conn conn=new Conn();
  29. this.con=conn.getConn();
  30. this.ps=con.prepareStatement(sql);
  31. if(parmates!=null && !parmates.equals("")){
  32. int index=1;
  33. for(String s:parmates){
  34. this.ps.setString(index, s);
  35. index++;
  36. }
  37. }
  38. this.rs=this.ps.executeQuery();
  39. while(rs.next()){
  40. Object o = clazz.newInstance();
  41. List<String> allMethods=getAllMethods(clazz);
  42. int index=1;
  43. for(String s:allMethods){
  44. clazz.getDeclaredMethod(s, String.class).invoke(o, rs.getString(index));
  45. index++;
  46. }
  47. all.add(o);
  48. }
  49. return all;
  50. }

发表评论

表情:
评论列表 (有 0 条评论,221人围观)

还没有评论,来说两句吧...

相关阅读