dictionaryjavabeanspropertydescriptor

Converting Map to Java Bean, some properties cannot be set rightly


// I use this simple program: public static Object convertToBean(Class type, Map map) { BeanInfo beanInfo; Object obj = null; try { beanInfo = Introspector.getBeanInfo(type); obj = type.newInstance();

            // When I debugging to here, I found that some properties is different from the variable the Object own. PropertyDescriptor changes charactor case when the variable is not in "String" type.
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor descriptor : propertyDescriptors) {
                String propertyName = descriptor.getName();

                if (map.containsKey(propertyName)) {
                    Object value = map.get(propertyName);
                    Object[] args = new Object[1];
                    args[0] = value;
                    descriptor.getWriteMethod().invoke(obj, args);
                }
            }
        } catch (Exception ignored) {
        }
        return obj;
    }

//Using BeanMap is the same question.

Solution

  • Finally I found the root cause. The problem solved by changing “A01” to "a01". The variable name must be strict camel rule. First character must be lower case, except first two characters are all in upper case, like "AD". Because the setter and getter methods will generate in same pattern. so It'll be difficult to recognize the real name of one variable.