?
1. ?Map ----> Object
?
?
public static <T> T mapToBean(Map<String, Object> map, Class<T> obj) throws Exception { if (map == null) { return null; } Set<Entry<String, Object>> sets = map.entrySet(); T t = obj.newInstance(); Method[] methods = obj.getDeclaredMethods(); for (Entry<String, Object> entry : sets) { String str = entry.getKey(); String setMethod = "set" + str.substring(0, 1).toUpperCase() + str.substring(1); for (Method method : methods) { if (method.getName().equals(setMethod)) { method.invoke(t, entry.getValue()); } } } return t; }
?
?
?
2. Object --> Map
?
?
public Map<String,Object> objectToMap(Object obj) { Map<String,Object> map = new HashMap<String,Object>(); Class<?> c = null; try { c = Class.forName(obj.getClass().getName()); Method[] m = c.getMethods(); for (int i = 0; i < m.length; i++) { String method = m[i].getName(); if (method.startsWith("get") && !method.equals("getClass")) { try { Object value = m[i].invoke(obj); if (value != null) { String key = method.substring(3); key = key.substring(0, 1).toLowerCase() + key.substring(1); map.put(key, value); } } catch (Exception e) { logger.error("出现错误"); e.printStackTrace(); } } } } catch (Exception e) { logger.error("出现错误"); e.printStackTrace(); } return map; }
?
?
?
?
原文:http://henu-zyy.iteye.com/blog/2265844