Skip to content

Instantly share code, notes, and snippets.

@HydrangeaPurple
Created May 11, 2022 01:25
Show Gist options
  • Save HydrangeaPurple/605be6ae27ba9d6f6b502935f62ff7fb to your computer and use it in GitHub Desktop.
Save HydrangeaPurple/605be6ae27ba9d6f6b502935f62ff7fb to your computer and use it in GitHub Desktop.
/**
* 对象转Map
*
* @param object
* @return
* @throws IllegalAccessException
*/
public static Map<String, Object> objectToMap(Object object) {
Map<String, Object> map = new HashMap<>();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
map.put(field.getName(), field.get(object));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return map;
}
/**
* map转对象
*
* @param map
* @param beanClass
* @param <T>
* @return
* @throws Exception
*/
public static <T> T mapToObject(Map<String, ?> map, Class<T> beanClass) throws Exception {
T object = beanClass.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);
if (map.containsKey(field.getName())) {
field.set(object, map.get(field.getName()));
}
}
return object;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment