Invoke Method using Reflection API

This example highlights the way how to invoke a method using the reflection API. As we are aware that we can dynamically invoke a method in another class by using the reflection classes. Note that using reflection is more expensive in terms of performance. This programming practice is used only in the certain requirements where project needs to create dynamic classes and invoked the methods on it where we are not knowing the class name at compile time. Here this example invoke the “append” method in the StringBuffer class using the reflection API.

  • First I have created a StringBuffer class anb called append method to add the string values.
  • Use getClass() API method to get the runtime class of the StringBuffer and then getMethod(String name, Class<?>… parameterTypes) API method of Class to get the Method object that reflects the specified public member method of the class or interface represented by this Class object.
  • Once got the Method object, use the invoke (object,args) to call the method with arguments which invokes the method from the underlying original class.

Lets look at the simple example to understand the code:

package javabeat.net.reflection;

import java.lang.reflect.Method;

public class InvokeMethodExample {

	public static void main(String[] args) throws Exception {

		StringBuffer strBuffer = new StringBuffer();

		strBuffer.append("JavaBeat Reflection Example");
		System.out.println("Original String : " + strBuffer);

		// Get the method name "append" using reflection
		Method appendMethod = strBuffer.getClass().getMethod("append", String.class);

		// Invoke method with arguments
		appendMethod.invoke(strBuffer, " Java Programming World!!");

		System.out.println("Invoked using Reflection: " + strBuffer);

	}
}

Output

Original String : JavaBeat Reflection Example
Invoked using Reflection: JavaBeat Reflection Example Java Programming World!!

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*