How to use Reflection in Java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sreekandank
    New Member
    • Jun 2009
    • 45

    How to use Reflection in Java

    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:
    • 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.
    1. Array
    2. Field
    3. Constructor
    4. Method
    5. 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);
      }
     }
    }
    Last edited by MMcCarthy; Nov 6 '11, 08:41 AM. Reason: adding code tags
Working...