/**
* 将对象转成map
* @param object
* @return
* @throws Exception
*/
public static Map<String, Object> beanToMap(Object object) throws Exception
{
Map<String, Object> map = new HashMap<String, Object>();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields)
{
field.setAccessible(true);
map.put(field.getName(), field.get(object));
}
return map;
}
/**
* map转对象
* @param <T>
* @param map
* @param beanClass
* @return
* @throws Exception
*/
@SuppressWarnings("rawtypes")
public static <T> T mapToBean(Map 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;
}
java实体类对象与map互转的方法
最新推荐文章于 2023-12-22 13:55:29 发布