Reflection is the ability of java program which allows to analyze itself. The java.lang.refle ct package provides the ability to obtain the information about the fields, constructors, methods and modifiers of a class.
A program that can analyze the capabilities of classes is called reflective.
The following are the four features of reflection:
The following are the important classes available in java.lang.refle ct package.
These classes are used to analyze about the fields, constructors, methods and modifiers.
The following simple program illustrates the concept of reflection.
ReflectionDemo. java
A program that can analyze the capabilities of classes is called reflective.
The following are the four features of reflection:
- Analyze the capabilities of class at run time
- Analyze objects at run time
- Write generic array code
- Method pointers
The following are the important classes available in java.lang.refle ct package.
- Array
- Field
- Constructor
- Method
- Modifier
These classes are used to analyze about the fields, constructors, methods and modifiers.
The following simple program illustrates the concept of reflection.
ReflectionDemo. java
Code:
import java.lang.reflect.*;
/**
*@author Sreekandan.K
*/
public class ReflectionDemo
{
public static void main(String args[])
{
try
{
String clsName="java.util.Date";
Class c=Class.forName(clsName);
System.out.println("Constructors...");
Constructor cnts[]=c.getConstructors();
for(int i=0;i<cnts.length;i++)
{
System.out.println(" "+cnts[i]);
}
System.out.println("Fields...");
Field flds[]=c.getFields();
for(int i=0;i<flds.length;i++)
{
System.out.println(" "+flds[i]);
}
System.out.println("Methods...");
Method mds[]=c.getMethods();
for(int i=0;i<mds.length;i++)
{
System.out.println(" "+mds[i]);
}
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
}