Wednesday, September 22, 2010

Reflections

Some imports that you may require

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


A generic method which can print any bean class, provided all the getter methods are there.


public static void printObject(Object app) throws
IllegalArgumentException, IllegalAccessException, 
InvocationTargetException
{
    Method[] m = app.getClass().getMethods();
    for(Method method : m)
    {
        if(method.getName().startsWith("get"))
        {
            // if getClass then ignore this method.
            if(method.getName().equals("getClass"))
                continue;
            if(method.getReturnType().isArray())
            {
                System.out.print(method.getName() + "=[ ");
                Object[] values = (Object[])method.invoke(app, null);

                for(Object v : values)
                {
                    System.out.print(v + ", " );
                }
                System.out.print(" ]\n");
            }          
            else
                System.out.println(method.getName() + " = " + method.invoke(app, null));
        }
    }  
}



If you would like to learn more about Reflections, you can visit this link: http://java.sun.com/developer/technicalArticles/ALT/Reflection/

1 comment:

  1. Please note that you need to change line number 16 if you are using JDK 1.6

    there you need to pass only 1 argument i.e. app

    The declaration of invoke method has been changed in 1.6

    ReplyDelete