Browse by Domains

Reflection in Java

Introduction

Reflection in java is an Application Programming Interface (API) that is used for examining or modifying the behaviour of interfaces, methods, classes at runtime.

The java. lang. Class classes provide many different methods that can be used for metadata, examine and change the behaviour of interfaces, methods, classes at run time. The java. lang and java. lang.reflect package provide required classes for the reflection.

Were Reflection Application Programming Interface (API) is mainly used : 

  1. IDE (Integrated Development Environment) like MyEclipse, Eclipse, NetBeans, etc.
  2. Debugger
  3. Test Tools, etc.

With the help of reflection we can invoke methods at runtime regardless of the access specifier used in them.

Fig : Reflection in Java

Reflection can be used to get the information about :

  1. Class : To know the name of the class to which that particular object belongs we can use the getClass() method.
  1. Constructors : To know the public constructors of the class to which that particular object belongs we can use the getConstructors() method.
  1. Methods : To know the public methods of the class to which that particular object belongs we can use the getMethods() method.

Check Out

Reflection of Java Classes

  1. Using forName() method : This method is used to load the class dynamically and return the instance of the Class class. The forName() method cannot be used for primitive types. 

Example :

class Animal {}   

class Dog
{  
public static void main ( String args[] )
{
Class a = Class.forName ( "Animal" );  
System.out.println ( a.getName() );  
}  
}  

Output :

Animal

  1. Using getClass() method : This method is used to return the instance of the Class class. The getClass() method is used if you know the tyoe and it can be also used with primitive types.  

Example :

class Animal {}  
  
class Dog
{  
void printName ( Object obj )
{  

Class b = obj.getClass();    
System.out.println ( b.getName() );  
  	}  

public static void main ( String args[] )
{  
   Animal s = new Animal();  
   
   Dog t = new Dog ();  
    t.printName ( s );  
}  
}

Output :

Animal

  1. Using .class extension : In java, if the type is available but there is no instance then we can obtain the Class by appending “.class” to the name of the type. This method is also useful for primitive data types.

Example :

class Dog
{  
  public static void main ( String args[] )
{  
  Class c1 = boolean.class;   
  System.out.println ( c1.getName() );  
  
   Class c2 = Dog.class;   
   System.out.println ( c2.getName() );  
 }  }

Output :

Boolean

Animal

Example of Java Class Reflection

In this example, there is a superclass “Animal” and a subclass “Cat”. In this, we are trying to inspect the class “Cat”.

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

class Animal {
}

// put this class in different Cat.java file

public class Cat extends Animal 
{
  public void display () 
{
    System.out.println ( "It’s a Cat." );
  }
}

// put this in Main.java file

class Main 
{
  public static void main ( String[] args )
 {
    try {
    
  // creating an object of Cat
      Cat a1 = new Cat();

      // creating an object of Class
      // by using getClass()
      Class obj = a1.getClass();

      // get the name of the class
      String name = obj.getName();
      System.out.println ( "Name : " + name );


      // get the access modifier of the class
      int modifier = obj.getModifiers();

      // converting the access modifier into the string
      String mod = Modifier.toString ( modifier );
      System.out.println ( "Modifier : " + mod );

      // get the superclass of Cat
      Class superClass = obj.getSuperclass();
      System.out.println ( "Superclass : " + superClass.getName() );
    }

    catch ( Exception e )
 {
      e.printStackTrace();
    }
  }
}

Output :

Name : Cat

Modifier : public

Superclass : Animal

In the above example, the statement : Class obj = a1.getClass();

In this statement we are trying to create an object “obj” of “Class” using the method “getClass()”. With the help of the object, the different methods of “Class” can be called.

  1. obj.getName() : This method is used to return the name of the class.
  2. obj.getModifiers() : This method is used to return the access modifier of the class.
  3. obj.getSuperclass() : This method is used to return the superclass of the class.

Reflecting Constructors, Methods and Fields

In java, we can inspect the constructors of an object’s class, methods and fields by using java reflection. This can be done by using the package java.lang.reflect which provides classes that can be used for manipulating the class members. 

  • Constructor Class It is used to give information about constructors in the class.
  • Method Class : It is used to give information about methods in the class.
  • Field Class : It is used to give information about fields in the class.
  1. Reflection of Constructors in Java

In Java, we can inspect various constructors using different methods provided by the Constructor class. It can be easily done by the java.lang.reflect.Constructor class.

Example :

In this example, there are two constructors, each having the class name “Bird”.

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

class Bird 
{

  // defining public constructor without parameter
  public Bird () {

  }

  // defining private constructor with a single parameter
  private Bird ( int age ) {

  }

}

class Main 
{
  public static void main(String[] args) 
{
    try 
{
      // create an object of Bird
      Bird a1 = new Bird ();

      // create an object of Class
      // by using getClass()
      Class obj = a1.getClass();

      // get all constructors of Bird
      Constructor[] constructors = obj.getDeclaredConstructors();

      for ( Constructor b : constructors )
 {

        // get the name of constructors
        System.out.println ( "Constructor Name : " + b.getName() );

        // getting the access modifier of constructors
        // converting it into string form
        int modifier = b.getModifiers();
        String mod = Modifier.toString ( modifier );
        System.out.println ( "Modifier : " + b.getModifiers() );

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

Output :

Constructor Name : Bird 

Modifier : public 

Parameters : 0

Constructor Name : Bird 

Modifier : private 

Parameters : 1

In the above example the statement : Constructor[] constructors = obj.getDeclaredConstructors(); we can access all the constructor in the class Bird and assign them in an array of constructors of Constructor type.

To fetch the information about the constructor we are using object ‘b’.

  1. b.getName() : It returns the name of the constructor.
  2. b.getModifiers() : It is used to return the access modifier of the constructor.
  3. b.getParameterCount() : It is used to return the number of parameters passed in each constructor.
  1. Reflection of Methods in Java

To get the information about different methods present in the class, we can use the Method Class that provides various methods. 

Example :

In this example, we are trying to get all the information about the method present in the “Bird” class.

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

class Bird 
{

  // methods of the class
  public void display() {
    System.out.println ( "It’s a Bird." );
  }

  private void type() {
    System.out.println ( “sparrow" );
  }
}

class Main 
{
  public static void main ( String args[] ) 
{
    try 
{

      // creating an object of Bird
      Bird d1 = new Bird ();

      // creating an object of Class by using getClass()
      Class obj = d1.getClass();

      // using object of Class to get all the declared methods of Bird
      Method[] methods = obj.getDeclaredMethods();

      // create an object of the Method class
      for ( Method c : methods ) 
     {

        // getting the names of methods
        System.out.println ( "Method Name : " + c.getName() );

        // getting the access modifier of methods
        int modifier = m.getModifiers();
        System.out.println( "Modifier : " + Modifier.toString(modifier) );

        // getting the return types of method
        System.out.println ( "Return Type : " + c.getReturnType() );
        System.out.println (" ");
      }
    }
    catch ( Exception e ) {
      e.printStackTrace();
    }
  }
}

Output :

Method Name : display

Modifier : public

Return Type : void

Method Name : type

Modifier : private

Return Type : void

The expression Method[] methods = obj.getDeclaredMethods(); returns all the methods present inside the class.

To fetch the information about the constructor we are using object ‘c’.

  1. c.getName() : It returns the name of the method.
  2. c.getModifiers() : It is used to return the access modifier of the method.
  3. c.getReturnType() : It is used to return the type of the method.
  1. Reflection of Fields in Java

Using the method of Field Class we can also inspect and modify the various field of the class. 

Example :

In this example, we have a class named “Bird”, that has a public field name “type”.

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

class Bird
 {
  public String type;
}

class Main 
{
  public static void main ( String args[] )
 {
    try 
{
      // creating an object of Dog
      Bird d1 = new Bird ();

      // creating an object of Class by using getClass()
      Class obj = d1.getClass();

      // accessing and setting the type field
      Field field1 = obj.getField ( "type" );
      field1.set ( d1, " sparrow " );

      // getting the value of the field type
      String typeValue = (String) field1.get(d1);
      System.out.println ( "Value : " + typeValue );

      // getting the access modifier of the field type
      int mod = field1.getModifiers();

      // convert the modifier to String form
      String modifier1 = Modifier.toString (mod);
      System.out.println ( "Modifier : " + modifier1 );
      System.out.println (" ");
    }
    
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Output :

Value : sparrow

Modifier : public

The expression Field field1 = obj.getField ( “type” ); is accessing the public field of the “Bird” class and assigning the value to the object “field1” of the “Field” class.

To fetch the information about the constructor we are using object ‘field1’.

  1. field1.set () : It is used to set the value of the field.
  2. field1.getModifiers() : It is used to return the value of the field in the form of an integer.
  3. field1.get () : It is used to return the value of the field.

Advantages of Reflection

In Java, reflection is helpful because it helps in dynamic retrieval of information of class and data structure by name. It also allows their manipulation within an executing program. This is an extremely powerful feature that is not available in other conventional languages like Pascal, C, Fortran or C++.

Java Reflection API helps to inspect interfaces, methods, classes at runtime without any prior information of their internals by compile time.

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top