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<>();
flist.add(c.getDeclaredFields());
flist.add(c.getSuperclass().getDeclaredFields());
for (int i = 0; i < flist.size(); i++) {
for (Field field : flist.get(i)) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = null;
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;
}
正在研究怎么将Map赋值到对象中(对象中有多个子对象),纠结(ー`´ー)
更新 2020-6-24 map赋值对象(很久之前写的,仅供参考)
public static <T> T mapToObject(Map<String, Object> map, T t, String[] excludeKeys) { Class beanClass = t.getClass(); String[] declaredFieldsName = getDeclaredFieldsName(beanClass); // if (ArrayUtils.isNotEmpty(excludeKeys)) { // MapUtil.(map, excludeKeys); // } for (Object k : map.keySet()) { Object v = map.get(k); if (ArrayUtils.contains(declaredFieldsName, k.toString())) { try { Field field = beanClass.getDeclaredField(k.toString()); field.setAccessible(true); field.set(t, v); } catch (Exception e) { LOGGER.error("map转对象错误",e); } } } return t; } public static String[] getDeclaredFieldsName(Class beanClass) { Field[] fields = beanClass.getDeclaredFields(); int size = fields.length; String[] fieldsName = new String[size]; for (int i = 0; i < size; i++) { fieldsName[i] = fields[i].getName(); } return fieldsName; }