`
wangshu3000
  • 浏览: 130685 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

利用反射遍历一个POJO对象的各个字段名及属性。。。

阅读更多
java 代码
  1. public class ReflectionFiledPrintTest {   
  2.     private String name = "GoGoGo";   
  3.   
  4.     private String city = "DoDoDo";   
  5.   
  6.     public String getCity() {   
  7.         return city;   
  8.     }   
  9.   
  10.     public void setCity(String city) {   
  11.         this.city = city;   
  12.     }   
  13.   
  14.     public String getName() {   
  15.         return name;   
  16.     }   
  17.   
  18.     public void setName(String name) {   
  19.         this.name = name;   
  20.     }   
  21.   
  22.     public static void main(String args[]) {   
  23.         Object obj = "222";   
  24.         System.out.println("111"+obj);   
  25.         ReflectionFiledPrintTest tfpt = new ReflectionFiledPrintTest();   
  26.         try {   
  27.             Class reClass = Class   
  28.                     .forName("reflection.ReflectionFiledPrintTest");   
  29.             Method methods[] = reClass.getDeclaredMethods();   
  30.             for (int i = 0; i < methods.length; i++) {   
  31.                 if (methods[i].getName().startsWith("get")) {   
  32.                     Object retobj = methods[i].invoke(tfpt, null);   
  33.                     System.out.println(methods[i].getName() + "="  
  34.                             + (String) retobj);   
  35.                 }   
  36.             }   
  37.         } catch (ClassNotFoundException e) {   
  38.             e.printStackTrace();   
  39.         } catch (IllegalArgumentException e) {   
  40.             e.printStackTrace();   
  41.         } catch (IllegalAccessException e) {   
  42.             e.printStackTrace();   
  43.         } catch (InvocationTargetException e) {   
  44.             e.printStackTrace();   
  45.         }   
  46.     }   
  47. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics