lundi 22 juin 2015

Reflection - read a property of type class rather than string or int

I'm using Reflection to read properties and their values of a class. There are Strings, Booleans and properties of a class type. How to get the value of the class type.

User.java

private String firstName;
private String lastName;
private SupportLangauge flang;
private SupportLangauge mlang;

SupportLanguage.java

private String languageCode;
private Boolean flang;
private Boolean mlang;

I am able to save the data of flang, mlang using reflection, but unable to read value. When I do read, the object is being returned. See sample below.

Result:

       "flang": "com.sample.entity.user.SupportLanguage@3080037d
          [\r\n     languageCode=EN_US\r\n]",
       "mlang": "com.sample.entity.user.SupportLanguage@3080037d
          [\r\n  languageCode=EN_US\r\n]",

My code below for saving the language types.

SavingUser.java

for (User user : CollectionsUtilService.nullGuard(userList)) {
 PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(
   user.getClass()).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (fieldValueMap.containsKey(propertyDescriptor.getName())) {
if   (propertyDescriptor.getPropertyType().getName().
 equalsIgnoreCase("com.sample.entity.user.SupportLanguage")) {
                    String langString =   fieldValueMap.
             get(propertyDescriptor.getName());
             SupportLanguage s = new SupportLanguage();
                    s.setLanguageCode(langString);
                    propertyDescriptor.getWriteMethod().invoke(user, s);
                }                   

            }
        }
    }

My Code for Reading the value;

RenderingUser.java

               if (propertyDescriptor.getPropertyType().
                 getName().equalsIgnoreCase
               ("com.sample.entity.
                  user.SupportLanguage")) {
                  Method m = propertyDescriptor.getReadMethod();
                  SupportLanguage s = new SupportLanguage();
                  System.out.println("m.invoke(SupportLanguage) " 
                  +  m.invoke(s));  





Aucun commentaire:

Enregistrer un commentaire