Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java reflection to create field/value hashmap

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.

like image 461
Joe Almore Avatar asked Nov 29 '11 06:11

Joe Almore


People also ask

How do you set a field in a reflection?

The set() method of java. lang. reflect. Field is used to set the value of the field represented by this Field object on the specified object argument to the specified new value passed as parameter.

How do you set a field value?

The SetFieldValue method sets the value of a field. Specifies the value that you want to place in the field. The data types of the field and the value you are assigning to the field must be the same or compatible. If the field allows nulls, you can assign a null.

How do you return a value from a HashMap?

get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.


2 Answers

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);

like image 61
Tao Zhang Avatar answered Oct 15 '22 07:10

Tao Zhang


    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);
        }
    }
like image 27
shift66 Avatar answered Oct 15 '22 06:10

shift66