• 通过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            }  
  • 相关阅读:
    mysql
    jQuery选择器
    使用JavaScript操作DOM节点元素的常用方法(创建/删除/替换/复制等)
    MVC2.0==>MVC3.0
    sql 邮件发送测试情况
    C#调用存储过程
    设计模式
    sql 分页
    SQL Server 存储过程(转载)
    sqlitehelper封装
  • 原文地址:https://www.cnblogs.com/jason123/p/7092008.html
Copyright © 2020-2023  润新知