View RSS Feed

My Java Tips

Using Reflection to run methods

Rate this Entry
by , 11-09-2011 at 06:59 PM (1103 Views)
Reflection is used when we want examine or modify the runtime behavior of applications running in the Java virtual machine. Java’s Reflection API provides very useful functionality for programmers. Here we will go through an example to understand what can be done with Reflection.

Consider the following class called Countries:

Java Code:
public class Countries {

String name;
String capital;

public void setName(String name) { = name;

public void setCapital(String capital) { = capital;

public void _getCountry(){
	System.out.println("Country: " + name);

public void _getCapital(){
	System.out.println("Capital: " + capital + " - " + name);

It has two setter methods that are used to set country name and its capital. Then we have two methods that are used to print useful information. These methods are not actually getters as they are not returning any thing. Please note that their names are starting with _get. This is done on purpose to distinguish these methods from other.

Now lets come to the main class named: RefTest.

Java Code:
import java.lang.reflect.*;
import java.util.Iterator;
import java.util.Vector;
public class RefTest {

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

Vector  vector= new Vector();
Countries obj = new Countries();

Countries obj1 = new Countries();

Countries obj2 = new Countries();

for(Method m: (Class.forName("Countries")).getMethods())
	Iterator it = vector.iterator();
} //if

} //for

} //main

} //class
We made three objects of class Countries and used setter methods to set values. We also added these objects into Vector called vector. This vector can store only objects of class Countries. This is generics introduced in Java 5.0.

Now we come to Reflection. We will get through all the methods of class Countries and will run only those that are starting with _get. Once we have the required method, we will use Iterator to call that method for all the objects stored in the Vector named vector. Invoke method is used to execute the method.


Country: France
Country: Germany
Country: Itlay
Capital: Paris - France
Capital: Berlin - Germany
Capital: Rome - Itlay

This is just a simple example of Reflection. You can do really interesting stuff using Reflection.

Submit "Using Reflection to run methods" to Facebook Submit "Using Reflection to run methods" to Digg Submit "Using Reflection to run methods" to Submit "Using Reflection to run methods" to StumbleUpon Submit "Using Reflection to run methods" to Google

Tags: None Add / Edit Tags
Java SE