dsa

Java Reflection

In this tutorial, we will learn reflection, a feature in Java programming that allows us to inspect and modify classes, methods, etc.

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 required classes for reflection are provided under java.lang.reflect package.
Reflection gives us information about the class to which an object belongs and also the methods of that class which can be executed by using the object.
Through reflection we can invoke methods at runtime irrespective of the access specifier used with them.

reflection
reflection
    Reflection can be used to get information about –
  • Class The getClass() method is used to get the name of the class to which an object belongs.
  • Constructors The getConstructors() method is used to get the public constructors of the class to which an object belongs.
  • Methods The getMethods() method is used to get the public methods of the class to which an objects belongs.

Example: Constructor reflection:

import java.lang.Class;
import java.lang.reflect.*;

class Dog {

   public Dog() {
      
   }
   public Dog(int age) {
      
   }

   private Dog(String sound, String type) {
      
   }
}

class ReflectionDemo {
   public static void main(String[] args) {
      try {
           Dog d1 = new Dog();
           Class obj = d1.getClass();

           // get all the constructors in a class using getDeclaredConstructor()
           Constructor[] constructors = obj.getDeclaredConstructors();

           for(Constructor c : constructors) {
           // get names of constructors
               System.out.println("Constructor Name: " + c.getName());

           // get access modifier of constructors
               int modifier = c.getModifiers();
               System.out.println("Modifier: " + Modifier.toString(modifier));

           // get the number of parameters in constructors
               System.out.println("Parameters: " + c.getParameterCount());
          }
       }
       catch(Exception e) {
           e.printStackTrace();
       }
    }
}

Output

Constructor Name: Dog
Modifier: public
Parameters: 0

Constructor Name: Dog
Modifier: public
Parameters: 1

Constructor Name: Dog
Modifier: private
Parameters: 2
    Advantages of Using Reflection:
  • Extensibility Features: An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
  • Debugging and testing tools: Debuggers use the property of reflection to examine private members on classes.