zoukankan      html  css  js  c++  java
  • 通过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            }  
  • 相关阅读:
    centos 编程环境
    git 安装 使用
    nodejs 笔记
    微信开发
    composer 使用笔记
    一:安装centos 7最小编程环境 xfce桌面
    二: 安装centos服务环境软件mysql httpd php
    我的通用程序规范及说明
    常用js代码集
    三 , lnmp 一键包安装使用
  • 原文地址:https://www.cnblogs.com/jason123/p/7092008.html
Copyright © 2011-2022 走看看