1 packagecn.lonelcoud.util;2
3 importcom.sun.deploy.util.StringUtils;4
5 importjava.lang.reflect.Field;6 importjava.text.SimpleDateFormat;7 import java.util.*;8
9 /**
10 * Created by lonecloud on 17/3/12.11 * 用于对Object进行解析并且转换成Map键值对的形式12 *13 *@authorlonecloud14 *@version1.015 */
16 public classObjectUtils {17
18 private static final String JAVAP = "java.";19 private static final String JAVADATESTR = "java.util.Date";20
21 /**
22 * 获取利用反射获取类里面的值和名称23 *24 *@paramobj25 *@return
26 *@throwsIllegalAccessException27 */
28 public static Map objectToMap(Object obj) throwsIllegalAccessException {29 Map map = new HashMap<>();30 Class> clazz =obj.getClass();31 System.out.println(clazz);32 for(Field field : clazz.getDeclaredFields()) {33 field.setAccessible(true);34 String fieldName =field.getName();35 Object value =field.get(obj);36 map.put(fieldName, value);37 }38 returnmap;39 }40
41 /**
42 * 利用递归调用将Object中的值全部进行获取43 *44 *@paramtimeFormatStr 格式化时间字符串默认2017-03-10 10:2145 *@paramobj 对象46 *@paramexcludeFields 排除的属性47 *@return
48 *@throwsIllegalAccessException49 */
50 public static Map objectToMapString(String timeFormatStr, Object obj, String... excludeFields) throwsIllegalAccessException {51 Map map = new HashMap<>();52
53 if (excludeFields.length!=0){54 List list =Arrays.asList(excludeFields);55 objectTransfer(timeFormatStr, obj, map, list);56 }else{57 objectTransfer(timeFormatStr, obj, map,null);58 }59 returnmap;60 }61
62
63 /**
64 * 递归调用函数65 *66 *@paramobj 对象67 *@parammap map68 *@paramexcludeFields 对应参数69 *@return
70 *@throwsIllegalAccessException71 */
72 private static Map objectTransfer(String timeFormatStr, Object obj, Map map, List excludeFields) throwsIllegalAccessException {73 boolean isExclude=false;74 //默认字符串
75 String formatStr = "YYYY-MM-dd HH:mm:ss";76 //设置格式化字符串
77 if (timeFormatStr != null && !timeFormatStr.isEmpty()) {78 formatStr =timeFormatStr;79 }80 if (excludeFields!=null){81 isExclude=true;82 }83 Class> clazz =obj.getClass();84 //获取值
85 for(Field field : clazz.getDeclaredFields()) {86 String fieldName = clazz.getSimpleName() + "." +field.getName();87 //判断是不是需要跳过某个属性
88 if (isExclude&&excludeFields.contains(fieldName)){89 continue;90 }91 //设置属性可以被访问
92 field.setAccessible(true);93 Object value =field.get(obj);94 Class> valueClass =value.getClass();95 if(valueClass.isPrimitive()) {96 map.put(fieldName, value.toString());97
98 } else if (valueClass.getName().contains(JAVAP)) {//判断是不是基本类型
99 if(valueClass.getName().equals(JAVADATESTR)) {100 //格式化Date类型
101 SimpleDateFormat sdf = newSimpleDateFormat(formatStr);102 Date date =(Date) value;103 String dataStr =sdf.format(date);104 map.put(fieldName, dataStr);105 } else{106 map.put(fieldName, value.toString());107 }108 } else{109 objectTransfer(timeFormatStr, value, map,excludeFields);110 }111 }112 returnmap;113 }114
115 }