bean转Map:
Map转bean:
完整代码:
点击查看代码
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
/**
* map转bean
* @author Sappy
* @date 3/7/2023 11:55:49
*/
public class MapBeanUtils {
private static Logger logger = LoggerFactory.getLogger(MapBeanUtils.class);
/**
* bean转Map
*
* @param obj
* @return
*/
public static Map<String, Object> object2Map(Object obj) {
Map<String, Object> map = new HashMap<>();
if (obj == null) {
return map;
}
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
try {
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
} catch (Exception e) {
logger.error("MapBeanUtils Convert ERROR!!!" , e);
}
return map;
}
/**
* Map转bean
*
* @param map
* @param clazz
* @return
*/
public static Object map2Object(Map<String, Object> map, Class<?> clazz) {
if (map == null) {
return null;
}
Object obj = null;
try {
obj = clazz.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()));
}
} catch (Exception e) {
logger.error("MapBeanUtils Convert ERROR!!!" , e);
}
return obj;
}
}