Tuesday, February 22, 2011

Dump an object

I believe this code can be sometimes useful to debug...
it dumps the value of all methods of an object starting with "get", "is" or "has"...


 public String dumpObject(Object theObject) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
  StringBuilder result = new StringBuilder();
  for (Method method : theObject.getClass().getDeclaredMethods()) {
   String methodName = method.getName();
   if (methodName.startsWith("get") || methodName.startsWith("has") ||methodName.startsWith("is") && method.getParameterTypes().length == 0) {
    result.append(methodName).append("=").append(method.invoke(theObject, null));
    result.append("\n");
   }
  }
  
  return result.toString();
 }



I am sure the same can be done with some Apache commons utility....

No comments: