将Map转换为Java Bean,无法正确设置某些属性

时间:2016-11-23 03:12:27

标签: dictionary javabeans propertydescriptor

//我使用这个简单的程序:     public static Object convertToBean(Class type,Map map){             BeanInfo beanInfo;             Object obj = null;             尝试{                 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.

1 个答案:

答案 0 :(得分:1)

最后我找到了根本原因。 通过将“A01”更改为“a01”解决了该问题。 变量名必须是严格的camel规则。第一个字符必须是小写字母,除了前两个字符都是大写字母,如“AD”。 因为setter和getter方法会生成相同的模式。所以很难识别出一个变量的真实名称。