Introduction To Reflection In Java

Introduction

 
In this article, we discuss reflection in Java. Reflection is the process of determining or modifying the behavior of a class at runtime. Java provides a java.lang.Class class that contains many methods, that help in finding metadata and to change the runtime behavior of a class.
 

What are the uses of Reflection?

 
It is mainly used in:
  • Integrated Development Environments (IDEs), for example, Eclipse, MyEclipse, NetBeans etcetera.
  • Test Tolls
  • Debugger etcetera.
This class generally used to performs two tasks
  • they have a method, that is used to find and changes the runtime behavior of a class.
  • they provide methods, that get the metadata of a class at runtime.

Some Drawbacks of reflection

  1. Performance overhead
  2. Security Restrictions
  3. Exposure of Internals
Some commonly used public methods of the Class class
  1. String getName()
  2. static Class forName(String className) throws ClassNotFoundException
  3. Object newInstnce() throws InstantiationException, IllegealAccessException
  4. boolean isInterface()
  5. boolean isArray()
  6. boolean isPrimitive()
  7. Class getSuperclass()
  8. Field[] getDeclaredFields() throws SecurityException
  9. Method[] getDeclaredMethods() throws SecurityException
  10. Constructor[] getDeclaredConstrutors() throws SecurityException
  11. Method getDeclaredMethod(String name, Class[] parameterTypes) throws NoSuchMethodException, SecurityException
How to determine the Object of the class at runtime
  1. By using forName() method.
  2. By using getClass() method
  3. By using .class syntax

1. Use of the forName() method

 
Example
  1. class Reflection {}  
  2. class Check {  
  3.  public static void main(String args[]) throws ClassNotFoundException {  
  4.   Class cls = Class.forName("Reflection");  
  5.   System.out.println(cls.getName());  
  6.  }  
  7. }   
Output
fig-1.jpg
 

2. By using the getClass() method

 
Example
  1. class Reflection {}  
  2. class Check {  
  3.  void printName(Object ob) {  
  4.   Class cls = ob.getClass();  
  5.   System.out.println(cls.getName());  
  6.  }  
  7.  public static void main(String args[]) {  
  8.   Reflection ref = new Reflection();  
  9.   Test tst = new Test();  
  10.   tst.printName(ref);  
  11.  }  
  12. }   
Output
 
fig-2.jpg
 

3. By using the .class syntax 

 
Example
  1. class Check {  
  2.  public static void main(String args[]) {  
  3.   Class cls1 = Check.class;  
  4.   System.out.println(cls1.getName());  
  5.   Class cls = boolean.class;  
  6.   System.out.println(cls.getName());  
  7.  }  
  8. }   
Output
 
fig-3.jpg