In my previous post i have shown you how to create an instance dynamically using java reflection. Here i will show you how to call a method dynamically using reflection.
Let us start with a simple example. Assume that the method name is refreshForm and it has no argument. You can get the method using class.getMethod(methodName) method and then call the method using method.invoke(instance of the class) method.
String className = "com.commlink.cbs.appclient.gl.ChartsOfAccount"
String methodName = "refreshForm";
//get the Class
Class class = Class.forName(className);
// get the instance
Object obj = class.newInstance();
// get the method
Method method = class.getMethod(methodName );
//call the method
method.invoke(obj);
Things will be little complex if the method has some arguments. Suppose the refreshForm method takes two String values. To call this method using reflection first create an array of Class and then an array of Object. Use the class array in getMethod method and the Object array in invoke method in the following way.
String className = "com.commlink.cbs.appclient.gl.ChartsOfAccount"
String methodName = "refreshForm";
Class class = Class.forName(className );
Object obj = class.newInstance();
//create the class array
Class[] types = new Class[] { String.class,String.class};
//get the method
Method method = class.getMethod(methodName ,types);
//create the object array
Object[] args = new Object[]{new String("Hello"), new String("World")};
//call the method
method.invoke(obj,args);