Reflection

Java Reflection is a process of examining or modifying the run time behavior of a class at run time.
The java.lang.Class class provides many methods that can be used to get metadata, examine and change the run time behavior of a class.
The java.lang and java.lang.reflect packages provide classes for java reflection.

Where it is used

The Reflection API is mainly used in:
  • IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.
  • Debugger
  • Test Tools etc.

How to get the object of Class class?

There are 3 ways to get the instance of Class class. They are as follows:
  • forName() method of Class class
  • getClass() method of Object class
  • the .class syntax

1) forName() method of Class class

  • is used to load the class dynamically.
  • returns the instance of Class class.
  • It should be used if you know the fully qualified name of class.This cannot be used for primitive types.
Let's see the simple example of forName() method.
  1. class Simple{}  
  2.   
  3. class Test{  
  4.  public static void main(String args[]){  
  5.   Class c=Class.forName("Simple");  
  6.   System.out.println(c.getName());  
  7.  }  
  8. }  
Output:Simple

2) getClass() method of Object class

It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives.
  1. class Simple{}  
  2.   
  3. class Test{  
  4.   void printName(Object obj){  
  5.   Class c=obj.getClass();    
  6.   System.out.println(c.getName());  
  7.   }  
  8.   public static void main(String args[]){  
  9.    Simple s=new Simple();  
  10.    
  11.    Test t=new Test();  
  12.    t.printName(s);  
  13.  }  
  14. }  
  15.    
Output:Simple

3) The .class syntax

If a type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type.It can be used for primitive data type also.
  1. class Test{  
  2.   public static void main(String args[]){  
  3.    Class c = boolean.class;   
  4.    System.out.println(c.getName());  
  5.   
  6.    Class c2 = Test.class;   
  7.    System.out.println(c2.getName());  
  8.  }  
  9. }  
Output:boolean
       Test

No comments:

Post a Comment