I recently came across this Java code snippet we created for Open-tides and still find it very useful in developing flexible and dynamic applications.
So, why is there a need to retrieve values using reflection? In our applications, there are two uses of this:
- Retrieving values for audit logging. In order to keep track of all changes in a record, the application must be able to identify changes in each of the field. To do this, we use reflection to browse through the fields and detect changes.
- Configurable Setting. Reflection can also be used to allow your application rules to be configurable by the user. For example, a notification facility that is triggered only when user defined criteria is satisfied. Configurable rules is certainly much better than hard-coded rules, it is dynamic and can be configured during runtime by the end-user and not the programmer.
So, here’s the piece of code that allows you to recursively retrieve object values through a standard Java object notation (e.g. employee.name, employee.office.location) that we have used for the features described above:
public static Object retrieveObjectValue(Object obj, String property) { if (property.contains(".")) { // we need to recurse down to final object String props[] = property.split("\\."); try { Object ivalue = null; if (Map.class.isAssignableFrom(obj.getClass())) { Map map = (Map) obj; ivalue = map.get(props[0]); } else { Method method = obj.getClass().getMethod(getGetterMethodName(props[0])); ivalue = method.invoke(obj); } if (ivalue==null) return null; return retrieveObjectValue(ivalue,property.substring(props[0].length()+1)); } catch (Exception e) { throw new InvalidImplementationException("Failed to retrieve value for "+property, e); } } else { // let's get the object value directly try { if (Map.class.isAssignableFrom(obj.getClass())) { Map map = (Map) obj; return map.get(property); } else { Method method = obj.getClass().getMethod(getGetterMethodName(property)); return method.invoke(obj); } } catch (Exception e) { throw new InvalidImplementationException("Failed to retrieve value for "+property, e); } } }
Hope this helps!
One thought on “Recursively Retrieving Values using Java Reflection”
Map.class.isAssignableFrom(obj.getClass())
should be written as
obj instanceof Map