Some pits of Object to Map

Here, three methods of Object mapping are summarized

1. Use reflection getDeclaredFields and getFields

     *  Clean the data of the incoming object, remove the null and '' property values, and store the other field names and property values in the map collection
    public  Map<String,Object> objectToMap(Object requestParameters) throws IllegalAccessException {

        Map<String, Object> map = new HashMap<>();
        // Get all property fields in the corresponding class of f object
        Field[] fields = requestParameters.getClass().getDeclaredFields();
        for (int i = 0, len = fields.length; i < len; i++) {
            String varName = fields[i].getName();
            // Get the original access control permission
            boolean accessFlag = fields[i].isAccessible();
            // Modify access control permissions
            // Get the variables in the object corresponding to the properties fields[i] in the object f
            Object o = fields[i].get(requestParameters);
            if (o != null && StringUtils.isNotBlank(o.toString().trim())) {
                map.put(varName, o.toString().trim());
                // Restore access control rights
        return map;

Pit by reflection,

1. getDeclaredFields can only return the fields of the Object, not the fields of the parent class. If you don't pay attention, you will lose the properties;
2. If the getFields method is used, only public fields can be returned, not privite private ones

2. Through apache's Utils

 public static Map<?, ?> objectToMap(Object obj) {
        if (obj == null) {
            return null;
        return new org.apache.commons.beanutils.BeanMap(obj);

apache's Utils pit

The returned beanmap extensions abstractmap is not a HashMap. Please note that

3. Through the PropertyDescriptor class of jdk

 public static Map<String, Object> objectToMap(Object obj) throws Exception {    
        if(obj == null)  
            return null;      
        Map<String, Object> map = new HashMap<String, Object>();   
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());    
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();    
        for (PropertyDescriptor property : propertyDescriptors) {    
            String key = property.getName();    
            if (key.compareToIgnoreCase("class") == 0) {   
            Method getter = property.getReadMethod();  
            Object value = getter!=null ? getter.invoke(obj) : null;  
            map.put(key, value);  
        return map;  

The propertydescriptors of the jdk are used here. Note that the getPropertyDescriptors method gets all fields. The first one is the class of the class. Note to judge

java.beans.PropertyDescriptor[name=class; propertyType=class java.lang.Class; readMethod=public final native java.lang.Class java.lang.Object.getClass()]

Tags: Java Apache JDK

Posted on Tue, 03 Dec 2019 00:12:25 -0500 by jackofalltrades