Alex Rivera | Logout

Java introspection: object to map

Asked 2011-07-22T21:11:11.850
47

I have a Java object obj that has attributes obj.attr1, obj.attr2 etc. The attributes are possibly accessed through an extra level of indirection: obj.getAttr1(), obj.getAttr2(), if not public.

The challenge: I want a function that takes an object, and returns a Map<String, Object>, where the keys are strings "attr1", "attr2" etc. and values are the corresponding objects obj.attr1, obj.attr2. I imagine the function would be invoked with something like

  • toMap(obj),
  • or toMap(obj, "attr1", "attr3") (where attr1 and attr3 are a subset of obj's attributes),
  • or perhaps toMap(obj, "getAttr1", "getAttr3") if necessary.

I don't know much about Java's introspection: how do you do that in Java?

Right now, I have a specialized toMap() implementation for each object type that I care about, and it's too much boilerplate.


NOTE: for those who know Python, I want something like obj.__dict__. Or dict((attr, obj.__getattribute__(attr)) for attr in attr_list) for the subset variant.

Edit
Report

2 Answers

48

Use Apache Commons BeanUtils: http://commons.apache.org/beanutils/.

An implementation of Map for JavaBeans which uses introspection to get and put properties in the bean:

Map<Object, Object> introspected = new org.apache.commons.beanutils.BeanMap(object); 

Note: despite the fact the API returns Map<Object, Object> (since 1.9.0), the actual class for keys in the returned map is java.lang.String

answered 2011-07-22T21:24:50.770
30

You can use JavaBeans introspection for this. Read up on the java.beans.Introspector class:

public static Map<String, Object> introspect(Object obj) throws Exception {
    Map<String, Object> result = new HashMap<String, Object>();
    BeanInfo info = Introspector.getBeanInfo(obj.getClass());
    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        Method reader = pd.getReadMethod();
        if (reader != null)
            result.put(pd.getName(), reader.invoke(obj));
    }
    return result;
}

Big caveat: My code deals with getter methods only; it will not find naked fields. For fields, see highlycaffeinated's answer. :-) (You will probably want to combine the two approaches.)

answered 2011-07-22T21:20:07.857

Your Answer