Map转JavaBean,部分属性设置不正确
Converting Map to Java Bean, some properties cannot be set rightly
// 我使用这个简单的程序:
public static Object convertToBean(Class type, Map 映射) {
BeanInfo beanInfo;
对象 obj = null;
尝试 {
beanInfo = Introspector.getBeanInfo(类型);
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.
终于找到了根本原因。
通过将“A01”更改为 "a01" 解决了问题。
变量名必须严格遵循骆驼规则。第一个字符必须是小写,除了前两个字符都是大写,如 "AD"。
因为 setter 和 getter 方法将以相同的模式生成。所以很难识别一个变量的真实名称。
// 我使用这个简单的程序: public static Object convertToBean(Class type, Map 映射) { BeanInfo beanInfo; 对象 obj = null; 尝试 { beanInfo = Introspector.getBeanInfo(类型); 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.
终于找到了根本原因。 通过将“A01”更改为 "a01" 解决了问题。 变量名必须严格遵循骆驼规则。第一个字符必须是小写,除了前两个字符都是大写,如 "AD"。 因为 setter 和 getter 方法将以相同的模式生成。所以很难识别一个变量的真实名称。