Tuesday, July 21, 2015

Reflection in JAVA

Reflection is a very useful approach to deal with the Java class at runtime, it can be used to load the Java class and call any of its methods.

Sample.java

public class Sample
{
  public void display1()
  {
    System.out.println("Inside 1");
  }
 
  public void display2()
  {
    System.out.println("Inside 2");
  }
 
  public void display3()
  {
    System.out.println("Inside 3");
   }
}

Now we can load this class(Sample) and call each of its methods at runtime.


ReflectionTest.java

public class ReflectionTest
{
  public static void main(String[] args)
  {
     Class cls=Class.forName("Sample");
     Object obj=cls.newInstance();

     Method method = cls.getDeclaredMethod("display1");
     method.invoke(obj);

     Method method = cls.getDeclaredMethod("display2");
     method.invoke(obj);

     Method method = cls.getDeclaredMethod("display3");
     method.invoke(obj);
  }


Springs framework also works on the principle of Reflection :)



 

No comments:

Post a Comment

Home