I have a Java object obj
that has attributes obj.attr1
, obj.attr2
etc. The attributes are possibly accessed through an extra level of
You can use JavaBeans introspection for this. Read up on the java.beans.Introspector
class:
public static Map introspect(Object obj) throws Exception {
Map result = new HashMap();
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.)