Recursively Retrieving Values using Java Reflection

May 2011 Posted by Allan Tan

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:

  1. 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.
  2. 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!

Related Posts with Thumbnails

About the Author

Allan Tan is a techno-preneur by heart with a passion for innovation and contribution.

One Response to “Recursively Retrieving Values using Java Reflection”

  1. August 16, 2011  |  8:43 am
    bob

    Map.class.isAssignableFrom(obj.getClass())

    should be written as

    obj instanceof Map

Leave a Reply

(required)
Copyright © 2012 Ideyatech, Inc. All Rights Reserved.