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            }  
  • 相关阅读:
    FTP文件传输应用分析
    A*寻路算法
    Asp.net页面事件引发后台程序处理原理
    开发人员的基本原则(转)
    定位new表达式
    常量对象的动态分配和释放
    PostThreadMessage使用
    最美丽的数学公式
    仿函数
    CF1598EStaircases【计数】
  • 原文地址:https://www.cnblogs.com/jason123/p/7092008.html
Copyright © 2011-2022 走看看