Wednesday, 11 January 2012

How to implement Reflection in J2SE

How to implement Reflection in J2SE


      In J2SE reflection is implemented using classes like Class, Method, Field, Constructor. Here I have given a simple example to understand the concept.

First make a Java file named TestReflect.java



//This class is made for testing the reflection facility provided by Java


class TestReflect
{
        //private data members
        int a=5,b=10,c=85;
        Integer in = new Integer(50);


        //other data members
        public int j=74;
        protected double m;
        public static int st;
       
        //constructors
        private TestReflect()     {    }
        protected TestReflect(int a, int b)   {    }
        TestReflect(TestReflect tr)    {    }
        public TestReflect(int i)  {   }


        //instance methods
        public void disp()    {  System.out.println("  display function  ");      }
        protected void getA()    {       }
        public void getM(double d)   {  System.out.println("Value passed is : "+d); }  
}

Now, to get the properties and methods of the above defined class dynamically define other java file name MyReflect.java



//This class will  make use of java.lang.reflect package


import java.lang.reflect.*;

public class MyReflect
{
      public static String getModifierNm(int modnm)
      {
String str = new String();
switch(modnm)
{
     case 0:str = "Default";
break;
     case 1:str = "Public";
break;
     case 2:str = "Private";
               break;
     case 4:str = "Protected";
break;
}
return str;
      }
       
      public static void main(String args[])
      {
 int ifor;

try
{
        //getting class name dynamically using static method forName() of class Class
     Class clsNm = Class.forName(args[0]);

      System.out.println(clsNm);
      System.out.println(clsNm.getName());
      System.out.println(clsNm.getSuperclass().getName());

      //getting constructors but only return public constructors
      Constructor cntr[] = clsNm.getConstructors();

      System.out.println("Getting public constructors");
       for(ifor=0;ifor<cntr.length;ifor++)
                               System.out.println(cntr[ifor].getName()+ "   ------------  "+cntr[ifor].getModifiers()+"  -----   "+getModifierNm(cntr[ifor].getModifiers()));

       System.out.println("Getting all the constructors");
              cntr = clsNm.getDeclaredConstructors();

         //displaying all the constructors with modifiers
       for(ifor=0;ifor<cntr.length;ifor++)
                               System.out.println(cntr[ifor].getName()+ "   ------------  "+cntr[ifor].getModifiers()+"  -----   "+getModifierNm(cntr[ifor].getModifiers()));


      //gives a list of only public fields
       Field field[] = clsNm.getFields();
     
       System.out.println("Fields got by method getFields()");
       for(ifor=0;ifor<field.length;ifor++)
              System.out.println(field[ifor].getName());

        //gives a list of all the declared fields private, public, protected and default
       field = clsNm.getDeclaredFields();
       Class tmpCls;
   
       System.out.println("Fields got by getDeclaredFields   -------  Getting type of the fields");
       for(ifor=0;ifor<field.length;ifor++)
       {
 tmpCls =  field[ifor].getType();
                    System.out.println(field[ifor].getName()+"  ----------   "+tmpCls.getName());
       }

        //getting values of the public fields
           field = clsNm.getDeclaredFields();
           int var = field[5].getInt(clsNm);
        System.out.println("Value of the first field is : "+var);

        //getting methods
       Method method[] = clsNm.getDeclaredMethods();

        System.out.println("Methods got by getDeclaredMethods()");
       for(ifor=0;ifor<method.length;ifor++)
              System.out.println(method[ifor].getName()   +   "   ------   "+method[ifor].getReturnType().getName());

    //create an instance of the given class at runtime    
       Object obj = cntr[0].newInstance();

   System.out.println("\nCalling disp method");
     method[0].invoke(obj);

   System.out.println("\nCalling getM() method with argument");
    method[2].invoke(obj,5.3);
}
catch(Exception e)
{
}
      }
}

/*    Compile the program in the command prompt

C:\Trupti\javaprac>javac MyReflect.java

Run the program and give the class name of which details you want using reflection

C:\Trupti\javaprac>java MyReflect TestReflect

The following will be the output,...

class TestReflect
TestReflect
java.lang.Object
Getting public constructors
TestReflect   ------------  1  -----   Public
Getting all the constructors
TestReflect   ------------  2  -----   Private
TestReflect   ------------  4  -----   Protected
TestReflect   ------------  0  -----   Default
TestReflect   ------------  1  -----   Public
Fields got by method getFields()
j
st
Fields got by getDeclaredFields   -------  Getting type of the fiel
a  ----------   int
b  ----------   int
c  ----------   int
j  ----------   int
m  ----------   double
st  ----------   int
in  ----------   java.lang.Integer
Value of the first field is : 0
Methods got by getDeclaredMethods()
disp   ------   void
getA   ------   void
getM   ------   void





No comments:

Post a Comment