利用反射遍历一个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. }  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值