Java Reflection

  • It is a mechanism of examining or modifying the run time behavior of a class at run time.
  • “The java.lang.Class” file 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.

Program: 1

import java.lang.reflect.Method; 
import java.lang.reflect.Field; 
import java.lang.reflect.Constructor; 
class TestReflection 
{ 
private String str; // creating a private field 
public Test ()  
{  
str = "Welcome to Reflection";
 } // creating a public constructor 
  
   
  public void method_1() // Creating a public method with no arguments 
 
 {   
 System.out.println("The string is " + str ); 
  } 
  
 public void method_2(int number) // Creating a public method with int as argument 
 
 {  
System.out.println("The number is " + number); 
 } 
  
 private void method_3() // creating a private method
{  
 System.out.println("Private method called"); 
 } 
 } 
  class DemoReflection 
{ 
    public static void main(String arg[]) throws Exception 
    { 
     TestReflection  obj_t = new TestReflection ();  // Creating object whose property is to be checked 
      
    Class cls_1 = obj_t.getClass(); 
    System.out.println("The name of class is " +  cls_1.getName());
    Constructor constructor_1 = cls_1.getConstructor(); 
    System.out.println("The name of constructor is " + constructor_1.getName()); 
     System.out.println("The public methods of the class are"); 
     Method [] methods_1 = cls_1.getMethods();    // Getting methods of the class through the object 
  
        for (Method method1: methods_1)  // Printing method names 
            System.out.println(method1.getName()); 
      
        Method methodcall_1 = cls_1.getDeclaredMethod("method2", 
                                                 int.class); 
        
        methodcall1.invoke(obj_t, 19);    // invokes the method at runtime 
        
        Field field = cls_1.getDeclaredField("str"); 
      
        field.setAccessible(true);     // allows the object to access the field irrespective 
     
        field.set(obj_t, "JAVA");  //takes object and the new value to be assigned to the field as arguments 
         
        Method methodcall_2 = cls_1.getDeclaredMethod("method1"); 
         
        methodcall_2.invoke(obj_t);  // invokes the method at runtime 
        
        Method methodcall_3 = cls_1.getDeclaredMethod("method3"); 
        
        methodcall_3. setAccessible(true);  
        // invokes the method at runtime 
        methodcall_3. invoke(obj_t); 
    } 
}

Output:

[box type=”shadow” align=”” class=”” width=””]

The name of the class is the Test

The name of the constructor is Test

The public methods of the class are: 

method2

method1

wait

wait

wait

equals

toString

hashCode

getClass

notify

notifyAll

The number is 19

The string is JAVA

Private method invoked

[/box]

2. Let’s see the example using the Get Interfaces

We will use the getInterfaces() method of the class to collect information about the interfaces implemented by the class. This method returns an array of interfaces.

Program:

import java.lang.Class;
import java.lang.reflect.*;
interface Animal {
   public void display();
}
interface Mammals {
   public void makeSound();
}
 
class Dog implements Animal, Mammals {
   public void display() {
      System.out.println("Hello dog.");
   }
 
   public void makeSound() {
      System.out.println("Bark bark");
   }
}
 
class ReflectionDemo {
  public static void main(String[] arg) {
      try {
          // create an object of Dog class
          Dog d1 = new Dog();
 
          // create an object of Class using getClass()
          Class obj = d1.getClass();
        
          // find the interfaces implemented by Dog
          Class[] objInterface = obj.getInterfaces();
          for(Class cl : objInterface) {
 
              // print the name of interfaces
              System.out.println("Interface Name is: " + cl.getName());
          }
      }
 
      catch(Exception ex) {
          ex.printStackTrace();
      }
   }
}

Output

[box type=”shadow” align=”” class=”” width=””]

Interface Name is: Animal

Interface Name is: Mammals

[/box]

3. Let’s learn the example using the Get Superclass and Access Modifier

We will use the method getSuperclass(), which can be used to retrieve the information about the superclass of a present class.

The class also provides a method getModifier() that returns the modifier of class in integer form.

A) Program using Get Superclass and Access Modifier

import java.lang.Class;
import java.lang.reflect.*;
 
interface Animal {
   public void display();
}
 
public class Dog implements Animal {
   public void display() {
       System.out.println("Hello dog.");
   }
}
class Reflection_Demo {
   public static void main(String[] arg) {
       try {
         Dog dg = new Dog();
           // create an object of Class using getClass()
           Class obj = dg.getClass();
            int modifiers = obj.getModifiers();
           System.out.println("Modifier: " + Modifier.toString(modifier));
 
           // Find the superclass of Dog
           Class superClass = obj.getSuperclass();
           System.out.println("Superclass: " + superClass.getName());
       }
 
       catch(Exception e) {
           e.printStackTrace();
       }
   }
}

Output:

[box type=”shadow” align=”” class=”” width=””]

Modifier: public

Superclass: Animal

[/box]

B) Program using Accessing Public Field

import java.lang.Class;
import java.lang.reflect.*;
class Dog {
  public String type;
}
class ReflectionDemo {
  public static void main(String[] args) {
     try{
         Dog d1 = new Dog();
        // create an object of the class Class
         Class obj = d1.getClass();
 
        // manipulating the public field type of Dog     
         Field field1 = obj.getField("type");
        // set the value of field
         field1.set(d1, "java");
      
         String typeValue = (String)field1.get(d1);  // get the value of field by converting in String
         System.out.println("type: " + typeValue);
 
         // get the access modifier of type
         int mod1 = field1.getModifiers();
         String modifier1 = Modifier.toString(mod1);
         System.out.println("Modifier: " + modifier1);
         System.out.println(" ");
     }
     catch(Exception e) {
         e.printStackTrace();
     }
  }
}

Output

[box type=”shadow” align=”” class=”” width=””]

type: labrador

Modifier: public

[/box]

Example: Accessing Private Field

import java.lang.Class;
import java.lang.reflect.*;
 
class Dog {
 private String color;
}
 
class ReflectionDemo {
public static void main(String[] args) {
   try {
      Dog d1 = new Dog();
      // create an object of the class Class
      Class obj = d1.getClass();
 
      // accessing the private field
      Field field2 = obj.getDeclaredField("color");
     
      // making the private field accessible
      field2.setAccessible(true);
      // set the value of color
      field2.set(d1, "brown");
      
      String colorValue = (String)field2.get(d1); // get the value of type converting in String
      System.out.println("color: " + colorValue);
 
      // get the access modifier of color
      int mod2 = field2.getModifiers();
      String modifier2 = Modifier.toString(mod2);
      System.out.println("modifier: " + modifier2);
   }
   catch(Exception e) {
      e.printStackTrace();
   }
 }
}

Output:

[box type=”shadow” align=”” class=”” width=””]

color: brown

modifier: private

[/box]

Example: Method Reflection

import java.lang.Class;
import java.lang.reflect.*;
 
class Dog {
   public void display() {
      System.out.println("I am a dog.");
   }
 
   protected void eat() {
      System.out.println("I eat dog food.");
   }
 
   private void makeSound() {
      System.out.println("Bark Bark");
   }
 
}
 
class ReflectionDemo {
   public static void main(String[] args) {
      try {
          Dog d1 = new Dog();   // create an object for the  Dog class
 
          // create an object of class
          Class obj = d1.getClass();
          
          // get all the methods using the getDeclaredMethod()
          Method[] methods = obj.getDeclaredMethods();
 
          // get the name of methods
          for(Method m : methods) {
               
             System.out.println("Method Name is: " + m.getName());
              
             // get the access modifier of methods
             int modifier = m.getModifiers();
             System.out.println("Modifier is: " + Modifier.toString(modifier));
              
             // get the return types of method
             System.out.println("The return type is void" + m.getReturnType());
             System.out.println(" ");
          }
       }
       catch(Exception exc) {
           exc.printStackTrace();
       }
   }
}

Output:

[box type=”shadow” align=”” class=”” width=””]

Method Name is: display

Modifier is: public

The return type is void.

Method Name is: eat

The modifier is: protected

The return type is void.

Method Name is: makeSound

The modifier is: private

The return type is void.

[/box]

4. Let’s have an example using Reflection of Constructor

We will use the different- different constructors of a class by using the various methods which are provided by the Constructor class.

a) getConstructors() – returns all public constructors of a class and superclass of the class

b) getDeclaredConstructor() – returns all the constructors

c) getName() – returns the name of constructors

d) getModifiers() – returns the access modifier of constructors in integer form

e) getParameterCount() – returns the number of parameters of constructors

Program using 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:

[box type=”shadow” align=”” class=”” width=””]

Constructor Name: Dog

Modifier: public

Parameters: 0

Constructor Name: Dog

Modifier: public

Parameters: 1

Constructor Name: Dog

Modifier: private

Parameters: 2

[/box]

Leave a Reply

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