package demo;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
public class ConvertUtil {
public static <T> T mapToObject(Map<String, Object> map, Class<T> beanClass) {
if (map == null) return null;
try {
T instance = beanClass.newInstance();
Field[] fields = instance.getClass().getDeclaredFields();
if (null != fields && fields.length > 0) {
for (Field field : fields) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)) {
continue;
}
field.setAccessible(true);
if (map.containsKey(field.getName())) {
field.set(instance, map.get(field.getName()));
}
}
}
return instance;
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public static Map<String, Object> objectToMap(Object obj) {
Class<?> beanClass = obj.getClass();
Map<String, Object> result = new HashMap<>();
Field[] fields = beanClass.getFields();
try {
for (Field field : fields) {
field.setAccessible(true);
result.put(field.getName(), field.get(obj));
}
return result;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
|