Java对象与Map的转换

来源:互联网 发布:u盘安装mac系统 编辑:程序博客网 时间:2024/05/19 05:30
 

Java对象与Map的转换

标签: javaexceptionobjectiteratorstringtypes
 21990人阅读 评论(1) 收藏 举报

 首先是将map和要被赋值的Bean传进来

[java] view plain copy
  1. public static void setValue(Map map,Object thisObj)  
  2. {  
  3.   Set set = map.keySet();  
  4.   Iterator iterator = set.iterator();  
  5.   while (iterator.hasNext())  
  6.   {  
  7.     Object obj = iterator.next();  
  8.     Object val = map.get(obj);  
  9.     setMethod(obj, val, thisObj);  
  10.   }  
  11. }  
  

 

调用设值方法setMethod方法(暂时只支持传入String类型字段的处理)

[c-sharp] view plain copy
  1. public static void setMethod(Object method, Object value ,Object thisObj)  
  2.   {  
  3.     Class c;  
  4.     try  
  5.     {  
  6.       c = Class.forName(thisObj.getClass().getName());  
  7.       String met = (String) method;  
  8.       met = met.trim();  
  9.       if (!met.substring(0, 1).equals(met.substring(0, 1).toUpperCase()))  
  10.       {  
  11.         met = met.substring(0, 1).toUpperCase() + met.substring(1);  
  12.       }  
  13.       if (!String.valueOf(method).startsWith("set"))  
  14.       {  
  15.         met = "set" + met;  
  16.       }  
  17.       Class types[] = new Class[1];  
  18.       types[0] = Class.forName("java.lang.String");  
  19.       Method m = c.getMethod(met, types);  
  20.       m.invoke(thisObj, value);  
  21.     }  
  22.     catch (Exception e)  
  23.     {  
  24.       // TODO: handle exception  
  25.       e.printStackTrace();  
  26.     }  
  27.   }  

 

 

以上是直接把map数据传进Bean

 

下面是把Bean转换成map对象输出

[c-sharp] view plain copy
  1. public static Map getValue(Object thisObj)  
  2.   {  
  3.     Map map = new HashMap();  
  4.     Class c;  
  5.     try  
  6.     {  
  7.       c = Class.forName(thisObj.getClass().getName());  
  8.       Method[] m = c.getMethods();  
  9.       for (int i = 0; i < m.length; i++)  
  10.       {  
  11.         String method = m[i].getName();  
  12.         if (method.startsWith("get"))  
  13.         {  
  14.           try{  
  15.           Object value = m[i].invoke(thisObj);  
  16.           if (value != null)  
  17.           {  
  18.             String key=method.substring(3);  
  19.             key=key.substring(0,1).toUpperCase()+key.substring(1);  
  20.             map.put(method, value);  
  21.           }  
  22.           }catch (Exception e) {  
  23.             // TODO: handle exception  
  24.             System.out.println("error:"+method);  
  25.           }  
  26.         }  
  27.       }  
  28.     }  
  29.     catch (Exception e)  
  30.     {  
  31.       // TODO: handle exception  
  32.       e.printStackTrace();  
  33.     }  
  34.     return map;  
  35.   }  

 

直接返回map,可以转换成json对象返回页面,便于Grid读取。

0 0
原创粉丝点击