Saturday, June 9, 2007

Using Reflections in Java

Reflection is a powerful approach to analyze the class at runtime. If new classes are added into your application dynamically then Reflection is used to get the structure of the class.

Reflection uses special kind of java class: Class. The object of the Class type can hold all the information of the class and also have its own methods to retrieve all the information.

This example code extracts the structure of the String class. It will display the name of the constructors, declared fields and methods to the console.

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionExample {

public static void main(String[] args) {
try {
Class cl = Class.forName("java.lang.String");
Constructor cnst[] = cl.getConstructors();
Field fld[] = cl.getDeclaredFields();
Method mtd[] = cl.getMethods();
System.out.println("Name of the Constructors of the String class");
for (int i = 0; i < cnst.length ; i++) {
System.out.println(cnst[i].getName());
}
System.out.println("Name of the Declared fields");
for (int i = 0; i < fld.length; i++) {
System.out.println(fld[i].getName());
}
System.out.println("Name of the Methods");
for (int i = 0; i < mtd.length; i++) {
System.out.println(mtd[i].getName());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

To find the structure details of user defined classes, we need not use the Class.forName() method. Instead simply give the class name itself. And don't forget to import the package of that class.

Example:

Class cl = Userdefinedclass.class;

The Class.forName() method searches for the class given as argument, in the Java Class Library.


No comments: