Created
May 11, 2022 01:25
-
-
Save HydrangeaPurple/605be6ae27ba9d6f6b502935f62ff7fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 对象转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