11

I need to create a Hashmap of field/values contained in an Entity, so I can can use them to replace them in a String containing tags with the field names.

I have this code:

public static String replaceTags(String message, Map<String, String> tags) ...

Which replaces all tags found in message for the equivalent values in tags, but in order to build the Map table I need to take "any" Entity and be able to create a Map from the Entity. So, how could I make that possible? to get a routine where I send the Entity and get as return a Map with all the fields and values.

public static Map<String, String> getMapFromEntity(Object entity){
    Map<String, String> map = new HashMap<String, String>();

    ...?????

    return map;
}

I know I could use reflection and this is the only approach I have found to get this done, but is there any other way to accomplish the same?, I mean a more efficient way.

Thanks.

Joe Almore
  • 4,036
  • 9
  • 52
  • 77

3 Answers3

14
    Field[] fields = entity.getClass().getFields();
    Map<String, String> map = new HashMap<String, String>();
    for(Field f : fields)
            map.put(f.getName(),(String) f.get(entity));

O, and your entity should be an object of your class, not your class itself. If your fields are private and you have getters for them, you should use getMethods() and check if method name starts with "get" prefix.Like this:

    Method[] methods = entity.getClass().getMethods();
    Map<String, String> map = new HashMap<String, String>();
    for(Method m : methods)
    {
        if(m.getName().startsWith("get"))
        {
            String value = (String) m.invoke(entity);
            map.put(m.getName().substring(3), value);
        }
    }
shift66
  • 11,760
  • 13
  • 50
  • 83
  • Hello Ademiban, thanks for the code, works very well!, even thought I also had to cast some of the values returned by the methods since not all of them are Strings, but this is simple once you have the main code. – Joe Almore Nov 29 '11 at 07:27
  • 5
    getters for booleans may start with "is" ;-). it is typically easier to get the value from fields directly after setting accessible to true but you could do methods too. – aishwarya Nov 29 '11 at 07:59
2

If all you want to get out of this is a map, why not use a literary like Jackson, then you can simply convert it like this Map map = new ObjectMapper().convertValue(object, Map.class);

Tao Zhang
  • 191
  • 2
  • 10
0

I know I could use reflection and this is the only approach I have found to get this done, but is there any other way to accomplish the same?

As far as I know, reflection is the only way to accomplish this, unless the class(es) you want to build the map from implement some interface, and your code extracting the map is aware of this interface.

esaj
  • 15,875
  • 5
  • 38
  • 52