How to call a method dynamically using Java Reflection

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);

4 comments:

Jonas Abreu May 12, 2009 at 9:10 AM  

maybe you'll like this project. It makes simplifies reflection using a DSL. http://projetos.vidageek.net/mirror/mirror

Unknown May 12, 2009 at 5:20 PM  

You project is really cool. Thanks for sharing...

Javin @ private and reflection June 5, 2012 at 12:10 AM  

One important point worth noting is that calling getDeclaredMethod() instead of getMethods(). former will return private methods as well as methods from super class. see how to invoke method by name in Java for complete details.

Shiva July 15, 2017 at 1:53 PM  

I was struggling with this for one day as my method contains different types of arguments. i was able to overcome the issue with the solution you have provided after searching so many websites. Thank you so much shams for the solution.

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers