2016-11-23 1 views
1

//この単純なプログラムを使用します: public static Object convertToBean(クラスタイプ、マップマップ){ BeanInfo beanInfo; オブジェクトobj = null; try { beanInfo = Introspector.getBeanInfo(タイプ); 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

は、例えば、私は豆、マップ内の データにマップを変換したい: A01-> 0.01; A02-> 0.02; AD - > "12345678" のJava Bean定義: プライベートダブルA01。プライベートDouble A02;プライベートString AD; セッターとゲッター。 ADは正しく設定できますが、A01とA02はnullになります。 – Victor

答えて

1

最後に根本的な原因が見つかりました。 "A01"を "a01"に変更して問題を解決しました。 変数名は厳密なラクダルールでなければなりません。最初の文字は小文字でなければなりません。ただし、最初の2文字はすべて大文字で、例えば「AD」です。 setterメソッドとgetterメソッドは同じパターンで生成されるためです。 1つの変数の実際の名前を認識するのは難しいでしょう。

関連する問題