0

I have class with some of variables.

How I can create map where key will be name of variable and value will be value of this variable ?

So I want to create:

Map<String, String> from custom object:

I create something like this:

protected Map<String, String> getObjectParams(Object object) throws Exception {
        Map<String, String> result = new HashMap<>();


        for (String field : (Iterable<String>) BeanUtils.describe(object).keySet()) {
            Object value = PropertyUtils.getProperty(object, field);
            if ((value != null) && (!"CLASS".equalsIgnoreCase(field)) {                     
                result.put(field, value.toString());
            }
        }

        return result;
}

but this will works only when class contains primitive objects and their wrapped equivalent. But when there will be another custom object with generated toString then there will value which I dont want. So how should I rewrite this example ?

UPDATE:

public Class MyCustomClass1 {


  MyCustomClass2 customClass2;
}

public Class MyCustomClass2 {

  String a;
  String b;
}

then map should contains value MyCustomClass2A and MyCustomClass2B and their values or something similar

hudi
  • 15,555
  • 47
  • 142
  • 246

2 Answers2

0

You will have to overload toString() method in your custom classes to get desired value. Something like :

public Class MyCustomClass1 {
  MyCustomClass2 customClass2;
  public String toString(){
      return customClass2.toString();
  }
}

public Class MyCustomClass2 {

  String a;
  String b;
  public String toString(){
          return a  + " " + b;
      }
}

This is just an example, change toString() as required.

Or use this how-to-get-the-list-of-all-attributes-of-a-java-object

Community
  • 1
  • 1
Himanshu Tyagi
  • 5,201
  • 1
  • 23
  • 43
  • In our application we already had custom toString methods which I cant override and also this doesnt help me because then in map will be key MyCustomClass2 and in value will be 2 values from this class which is wrong – hudi Jun 02 '14 at 12:24
  • 1
    Try this [link](http://stackoverflow.com/questions/1038308/how-to-get-the-list-of-all-attributes-of-a-java-object-using-beanutils-introspec) – Himanshu Tyagi Jun 02 '14 at 12:30
  • sorry but I dont understand how this link should helps me. It return string of class in really different format – hudi Jun 03 '14 at 06:59
0

Update return type to Map or Map and use recursion to populate child objects.

Asheesh Gupta
  • 318
  • 3
  • 4