What is the method for converting an object to a map in…

There are several ways to convert an Object to a Map in Java.

  1. By using Java reflection mechanism, extract all fields from an Object using Java reflection, then store the field names as keys and the field values as values into a Map.
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
    Map<String, Object> map = new HashMap<>();
    Class<?> clazz = obj.getClass();
    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);
        map.put(field.getName(), field.get(obj));
    }
    return map;
}
  1. To use the get method of a JavaBean: Retrieve the property value of an object using the get method of the JavaBean, then store the property name as the key and the property value as the value in a Map.
public static Map<String, Object> objectToMap(Object obj) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
    Map<String, Object> map = new HashMap<>();
    BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        String key = propertyDescriptor.getName();
        if (!key.equals("class")) {
            Method getter = propertyDescriptor.getReadMethod();
            Object value = getter.invoke(obj);
            map.put(key, value);
        }
    }
    return map;
}
  1. Utilize third-party libraries such as Apache Commons BeanUtils or Spring’s BeanUtils for a more straightforward way to convert objects into maps.

Utilize Apache Commons BeanUtils:

import org.apache.commons.beanutils.BeanUtils;

public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    Map<String, Object> map = new HashMap<>();
    map = BeanUtils.describe(obj);
    map.remove("class");
    return map;
}

Utilize Spring’s BeanUtils:

import org.springframework.beans.BeanUtils;

public static Map<String, Object> objectToMap(Object obj) {
    Map<String, Object> map = new HashMap<>();
    BeanUtils.copyProperties(obj, map);
    return map;
}
bannerAds