com.mybatiseasy.core.utils.BeanMapUtil Maven / Gradle / Ivy
package com.mybatiseasy.core.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BeanMapUtil {
/**
* 对象转Map
* @param object 对象
* @return Map
* @throws Exception ex
*/
public static Map beanToMap(T object) throws Exception {
Map map = new HashMap<>();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(object));
}
return map;
}
/**
* map转对象
* @param map Map
* @param beanClass 对象类
* @return 对象
* @param 对象类型
* @throws Exception ex
*/
public static T mapToBean(Map map, Class beanClass) throws Exception {
T object = beanClass.getDeclaredConstructor().newInstance();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
String snakeName = StringUtil.camelToSnake(field.getName());
if (map.containsKey(snakeName)) {
field.set(object, ConversionUtil.convertValue(map.get(snakeName), field.getType()));
}
}
return object;
}
public static List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy