Jun 052011
 

Very useful for logging and debugging.

package sactosoft.beanviewer;

import java.lang.reflect.Method;

/**
 * Displays an object propeties as property=value
 * 
 * 
 * Need to make it display object properties recursivly 
 * Usage: BeanViewer.view(object)
 * 
 * 
 * @author sactosoft
 * 
 */
public class BeanViewer {
    public static void view(Object obj) {
        Class c = obj.getClass();
        Method[] m = c.getMethods();
        for (int i = 0; i < m.length; i++) {
            String mName = m[i].getName();
            if (mName.startsWith("get")) {
                Class[] parameterTypes = m[i].getParameterTypes();
                if (parameterTypes.length == 0) {
                    Object result = null;
                    try {
                        result = m[i].invoke(obj, parameterTypes);
                    } catch (Exception e) {
                        System.out.println("BeanViewer failed. ");
                        e.printStackTrace();
                    }
                    System.out.print(mName.substring(3) + "=" + result + " | ");
                }
            }
        }
        System.out.println("");
    }
}