java关于实体对象与map之间的转换

一.对象转map

public static Map objectToMap(Object obj) throws IllegalAccessException {
    Map map = new HashMap<>();
    Class clazz = obj.getClass();
    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Object value = field.get(obj);
        map.put(fieldName, value);
    }
    return map;
}

二. map转对象

public static Object mapToObject(Map map, Class beanClass) throws Exception {
    if (map == null) {
        return null;
    }
    Object obj = beanClass.newInstance();

    BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor property : propertyDescriptors) {
        Method setter = property.getWriteMethod();
        if (setter != null) {
            setter.invoke(obj, map.get(property.getName()));
        }
    }

    return obj;
}

 

 

 

你可能感兴趣的:(#,工具方法)