通过Java的反射动态调用类的set和get方法

方法一:

 1  public static void main(String[] args) throws Exception {  
 2   Class clazz = Class.forName("TaskProvidePropsList");//这里的类名是全名。。有包的话要加上包名  
 3   Object obj = clazz.newInstance();  
 4   Field[] fields = clazz.getDeclaredFields();  
 5   //写数据  
 6   for(Field f : fields) {  
 7    PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);  
 8    Method wM = pd.getWriteMethod();//获得写方法  
 9    wM.invoke(obj, 2);//因为知道是int类型的属性,所以传个int过去就是了。。实际情况中需要判断下他的参数类型  
10   }  
11   //读数据  
12   for(Field f : fields) {  
13    PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);  
14    Method rM = pd.getReadMethod();//获得读方法  
15    Integer num = (Integer) rM.invoke(obj);//因为知道是int类型的属性,所以转换成integer就是了。。也可以不转换直接打印  
16    System.out.println(num);  
17   }  
18  }  
19 }  
 1 public static void getMethodDemo2() throws Exception {
 2         Class clazz = Class.forName("com.itcast.day26.Person");
 3         //Field field = clazz.getDeclaredField("name");
 4         Object obj = clazz.newInstance();
 5         
 6         PropertyDescriptor pd = new PropertyDescriptor("name", clazz);
 7         Method get = pd.getReadMethod();
 8         String name = (String)get.invoke(obj);
 9         System.out.println(name);
10     }

方法二:

1 public Object getValue(Object dto,String name) throws Exception{  
2            Method[]  m = dto.getClass().getMethods();  
3            for(inti=0;i<m.length;i++){  
4            if(("get"+name).toLowerCase().equals(m[i].getName().toLowerCase())){  
5                return  m[i].invoke(dto);  
6             }  
7            }  

 

转载于:https://www.cnblogs.com/jason123/p/7092008.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值