package com.zteits.pay.weixin.util; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; /*** * * Copyright: Copyright (c) 2017 ZTE-ITS * * @ClassName: MapUtil.java * @Description: map object互转 * @version: v1.0.0 * @author: wangbiao * @date: 2017年5月16日 上午10:13:08 * Modification History: * Date Author Version Description *---------------------------------------------------------* * 2017年5月16日 wangbiao v1.0.0 创建 */ public class MapUtil { /** * object转map * @param obj * @return * @throws Exception */ public static Map objectToMap(Object obj) throws Exception { if(obj == null){ return null; } Map map = new HashMap(); Field[] declaredFields = obj.getClass().getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); map.put(field.getName(), (String) field.get(obj)); } return map; } /*** * map转object * @param map * @param beanClass * @return * @throws Exception */ public static Object mapToObject(Map map, Class beanClass) throws Exception { if (map == null) return null; Object obj = beanClass.newInstance(); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { int mod = field.getModifiers(); if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){ continue; } field.setAccessible(true); field.set(obj, map.get(field.getName())); } return obj; } }