Home Java Reflect How to Invoke method using Reflection API of Java?
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

How to Invoke method using Reflection API of Java?

Advertisement
In this tutorial we will use the Reflection API of the Java to call a method in runtime. The Java Reflection API allows the developers to create the instance of the class in runtime and then call the methods of the class.

Example program for invoking the methods of a class using Reflection Framework

In this example I will teach you how to use the Java Reflection API for invoking the a method of a class in runtime. With the help of this example you will learn the use of Reflection API in Java.

The Reflection API of Java allows the developers to write code which can be used to invoke the methods of another class in runtime. For this you have to create the instance of the another class in runtime using Reflection API and then use the invoke method of the reflection API.

You should be aware of the performance of the Reflection API as it is more expensive and there is performance overhead. So, you should use the reflection API in certain conditions where you have to create the dynamic classes and call the methods in runtime. In normal programming you should not use the reflection framework to create the classes dynamically.

In this example we will show you how to use the "concat" method of the String class.

Here is the definition of the concat method of the String class:

String concat(String str)

The concat method of the String class takes string as a input parameter and concatenates the specified string to the end of this string.

We will show you how to call the concat method of the String class dynamically.

Java Reflection Framework example

Following is the steps to call the concat method of String class using Reflection framework:

Step 1: First of all we have to create a Class object for the class whose method is to be invoked. Here we have used the code: Class cls = String.class;. There are many ways to get the objects of a class.

Step 2: Now create a Method object by invoking getMethod on the Class object.  Following code is used in our example:

Method concatMethod = 
         cls.getMethod("concat", parametertype);

Step 3: Now we have to call the invoke method to call the method. We have used the following code in our example program:

result = (String)
         concatMethod.invoke(firstName,arguments);

Here is the complete code of the program that calls the "concat" method on the String class:

CallingMethod.java

import java.lang.reflect.*;

public class CallingMethod {
   public static void main(String[] args) {
      String firstName= new String("Deepak");
      String lastName=new String("Kumar");
      String result =  new String("");
      Class cls = String.class;
      Class[] parametertype = new Class[] {String.class};
      Object[] arguments = new Object[] {lastName};
      try {
         Method concatMethod = 
         cls.getMethod("concat", parametertype);
         result = (String)
         concatMethod.invoke(firstName,arguments);
         System.out.println(" Concatenated String is =>
         "+result);
         }catch (Exception e) {
         System.out.println(e);
         }
     }
}  

Output:

If you run the program it will display the following output:

Download this Example Code

In this above example code you have learned how to call the "concat" method dynamically using the Reflection framework of Java.

Example of calling "append" method of StringBuffer class

Now we will learn how to call the "append" method of StringBuffer class using the Java Reflection API. Here is the signature of the append method of the StringBuffer class:

public StringBuffer append(String s)

The append method is used to append the specified string to the character sequence.

Here is the example code:

import java.lang.reflect.Method;
public class ReflectionExample {
	public static void main(String[] args) throws Exception {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("Java Reflection Framework Example - RoseIndia.Net");
		System.out.println("Unmodifed String: " + stringBuffer);
		// Get the  "append" method using the Java reflection API
		Method method = stringBuffer.getClass().getMethod("append", String.class);
		// Invoke the append method
		method.invoke(stringBuffer, 
               " Hello This is an example of invoking method on the StringBuffer class.");
		System.out.println("String After appending: " + stringBuffer);
	}
}

In the above example code we have used the following method:

Method method = stringBuffer.getClass().getMethod("append", String.class);

to get the "append" method and using following code we are calling it using following code:

method.invoke(stringBuffer,
" Hello This is an example of invoking method on the StringBuffer class.");

You can download the source code through following link:

Download the code of append method on StringBuffer class

If you run the code it will give you following output:

D:\>javac ReflectionExample.java
D:\>java ReflectionExample
Unmodifed String: Java Reflection Framework Example - RoseIndia.Net
String After appending: Java Reflection Framework Example - RoseIndia.Net Hello This is an example of invoking method on the StringBuffer class.
D:\>

More tutorials of Reflection framework:

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 18, 2014

Related Tutorials

Ask Questions?    Discuss: How to Invoke method using Reflection API of Java?  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com