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
- Array
- Field
- Constructor
- Method
- Modifier
The following simple program illustrates the concept of reflection.
ReflectionDemo.java
Expand|Select|Wrap|Line Numbers
- 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);
- }
- }
- }