2016-11-23 64 views
1

//我使用這個簡單的程序: public static Object convertToBean {Class type,Map map} {BeanType} beanInfo; Object obj = null; 嘗試beanInfo = Introspector.getBeanInfo(type); obj = type.newInstance();將地圖轉換爲Java Bean,某些屬性無法正確設置

  // 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. 
+0

例如,我要地圖轉換爲一個Bean,在地圖數據 : A01-> 0.01; A02-> 0.02; AD - > 「12345678」 Java Bean的定義: 私人雙A01;私人雙A02;私人String AD; 二傳手和吸氣者。 然後可以正確設置AD,但A01和A02將爲空。 – Victor

回答

1

最後我找到了根本原因。 通過將「A01」更改爲「a01」解決了該問題。 變量名稱必須嚴格駱駝規則。第一個字符必須是小寫,除了前兩個字符全部大寫,如「AD」。 因爲setter和getter方法會以相同的模式生成。所以很難識別一個變量的真實姓名。