将Map转换为Obj的工具类
2015-08-27 19:48
363 查看
将Map转换为Obj的工具类
/** * * 将Map转换为Obj的工具类 * Created by sjyBing on 2015/8/27 0027. */ public class Map2ObjUtils { public static void Map2Entity(Map map, Object thisObj) { Set set = map.keySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Object obj = iterator.next(); Object val = map.get(obj); setObjMethod(obj, val, thisObj); } } public static Map Entity2Map(Object thisObj) { Map map = new HashMap(); Class c; try { c = Class.forName(thisObj.getClass().getName()); Method[] m = c.getMethods(); for (int i = 0; i < m.length; i++) { String method = m[i].getName(); if (method.startsWith("get")) { try{ Object value = m[i].invoke(thisObj); if (value != null) { String key=method.substring(3); key=key.substring(0, 1).toLowerCase()+key.substring(1); map.put(key, value); } }catch (Exception e) { System.out.println("error:"+method); } } } } catch (Exception e) { e.printStackTrace(); } return map; } private static void setObjMethod(Object method, Object value, Object thisObj) { Class c; try { c = Class.forName(thisObj.getClass().getName()); String met = (String) method; met = met.trim(); if (!met.substring(0, 1).equals(met.substring(0, 1).toUpperCase())) { met = met.substring(0, 1).toUpperCase() + met.substring(1); } if (!String.valueOf(method).startsWith("set")) { met = "set" + met; } Class types[] = new Class[1]; types[0] = Class.forName("java.lang.String"); Method m = c.getMethod(met, types); m.invoke(thisObj, value); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args){ Map<String, String> parms = new HashMap<String, String>() ; parms.put("callback","callback"); parms.put("url","url1"); parms.put("ip","ip1"); parms.put("id","id1"); parms.put("key","key1"); parms.put("index","index1"); parms.put("type", "type1"); parms.put("name", "name1"); NanoHttpEntiy obj = new NanoHttpEntiy(); Map2Entity(parms, obj); System.out.println("obj.getName():" + obj.getName()); Map<String, String> newParms = Entity2Map(obj); System.out.println("newParms.get:" + newParms.get("name")); } }
相关文章推荐
- UVa 11175:From D to E and back(图论)
- 无需看到你的脸就能认出你——实现Beyond Frontal Faces: Improving Person Recognition Using Multiple Cues
- Hadoop发展历史简介
- 游标的用法
- Linux内核工程导论——CGroup子系统
- 解决CSS中float:left后需要clear:both清空的繁琐步骤
- 指针学习
- 小猪二手车 v4.1 安卓版
- C语言基础知识之(九):函数
- WINDOWS API学习笔记之创建线程
- 数据结构--图 的JAVA实现(上)
- CF 161D Distance in Tree 树形DP
- ActiveMQ简介
- Android虚拟机启用中文输入法及其它常用配置
- hdu 1106 排序
- Android UI设计:AlertDialog
- UrlRewritingNet伪静态的使用方法与解决方案(URL重写)
- the last lecture
- 7 天玩转 ASP.NET MVC — 第 7 天
- iOS-UIViewController的UIView生命周期