携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第十六天,点击查看活动详情
由于公司使用的对象比较多,且一层层嵌套,于是准备转为Map来进行操作,研究了一下对象通过反射转为Map(对象中有多个对象)
private static final String JAVAP = "java.";
private static final String JAVADATESTR = "java.util.Date";
/**
* 利用递归调用将Object中的值全部进行获取
*
* @param timeFormatStr 格式化时间字符串默认<strong>2017-03-10 10:21</strong>
* @param c 对象
* @return
* @throws IllegalAccessException
*/
public static Map<String, String> objectToMapString(String timeFormatStr, Class<?> c, Object o) throws IllegalAccessException {
Map<String, String> map = new HashMap<>();
objectTransfer(timeFormatStr, c, o, map);
return map;
}
/**
* 递归调用函数
*
* @param timeFormatStr 时间格式
* @param c 父类
* @param o key(父对象)
* @param map 返回的map
* @return
* @throws IllegalAccessException
*/
private static Map<String, String> objectTransfer(String timeFormatStr, Class<?> c, Object o, Map<String, String> map) throws IllegalAccessException {
boolean isExclude = false;
//默认字符串
String formatStr = "YYYY-MM-dd HH:mm:ss";
//设置格式化字符串
if (timeFormatStr != null && !timeFormatStr.isEmpty()) {
formatStr = timeFormatStr;
}
List<Field[]> flist = new ArrayList<>();
//获得某个类的所有声明的字段,即包括public、private和proteced,但是不包括父类的申明字段。
flist.add(c.getDeclaredFields());
//获取父类的所有声明的字段,即包括public、private和proteced,但是不包括父类的申明字段。
flist.add(c.getSuperclass().getDeclaredFields());
for (int i = 0; i < flist.size(); i++) {
//循环所有字段
for (Field field : flist.get(i)) {
//由于JDK的安全检查耗时较多.所以通过setAccessible(true)的方式关闭安全检查就可以达到提升反射速度的目的
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(o);
if (value != null) {
Class<?> valueClass = value.getClass();
//判断是否是基本类型
if (valueClass.isPrimitive()) {
map.put(fieldName, value.toString());
} else if (valueClass.getName().contains(JAVAP)) {//判断是不是定义的类型
if (valueClass.getName().equals(JAVADATESTR)) {
//格式化Date类型
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
Date date = (Date) value;
String dataStr = sdf.format(date);
map.put(fieldName, dataStr);
} else {
map.put(fieldName, value.toString());
}
} else {
//递归子对象 valueClass 子对象的class ,value 子对象
objectTransfer(timeFormatStr, valueClass, value, map);
}
}
}
}
return map;
}