What is Reflection?

In Java, the process of analysing and modifying all the capabilities of a class at runtime is called Reflection.

Reflection API in Java is used to manipulate class and its members which include fields, methods, constructor, etc. at runtime.

One advantage of reflection API in java is, it can manipulate private members of the class too.

The java.lang.reflect package provides many classes to implement reflection java.Methods of the java.lang.Class class are used to gather the complete metadata of a particular class.

In this tutorial, you will learn-

Class in java.lang.reflect Package

Following is a list of various Java classes in java.lang.package to implement reflection-

  • Field: This class is used to gather declarative information such as datatype, access modifier, name and value of a variable.
  • Method: This class is used to gather declarative information such as access modifier, return type, name, parameter types and exception type of a method.
  • Constructor: This class is used to gather declarative information such as access modifier, name and parameter types of a constructor.
  • Modifier: This class is used to gather information about a particular access modifier.

Methods used in java.lang.Class

  • Public String getName (): Returns the name of the class.
  • public Class getSuperclass(): Returns the super class reference
  • Public Class[] getInterfaces() : Returns an array of interfaces implemented by the specified class
  • Public in getModifiers (): Returns an integer value representing the modifiers of the specified class which needs to be passed as parameter to "public static String toString (int i )" method which returns the access specifier for the given class.

How to get complete information about a class

  • To get information about variables, methods and constructors of a class, we need to create an object of the class.

    Java Reflection API - Tutorial

  • Following example shows different ways to create object of class "class" :

Java Reflection Example

Following example shows how to get metadata such as: Class name, super class name, implemented interfaces, and access modifiers of a class.

We will get the metadata of below class named Guru99Base.class:

Java Reflection API - Tutorial

  1. Name of the class is: Guru99Base
  2. It's access modifiers are: public and abstract
  3. It has implemented interfaces: Serializable and Cloneable
  4. Since it has not extended any class explicitly, it's super class is: java.lang.Object
  • Below class will get the meta data of Guru99Base.class and print it:

Java Reflection API - Tutorial

  1. print the name of the class using getName method
  2. Print the name of the super class using getSuperClass().getName() method
  3. Print the name of the implemented interfaces
  4. Print the access modifiers used by the class

Java Reflection API - Tutorial

Java Reflection API - Tutorial

Java Reflection Example

Following examples shows how to get metadata of a variable:
  • Here, we are creating a class named Guru99VariableMetaData .class with some variables:
package guru;
public class Guru99VariableMetaData {				
               public static int guru99IntVar1=1111;
               static int guru99IntVar2=2222;							
               static String guru99StringVar1="guru99.com";							
                static String guru99StringVar2="Learning Reflection API";    
}	
  • Steps to get the metadata about the variables in the above class:
  1. Create the class object of the above class i.e. Guru99VariableMetaData.class as below:
      Guru99VariableMetaData  guru99ClassVar  = new Guru99VariableMetaData();
      Class  guru99ClassObjVar  = guru99ClassVar.getClass();
  2. Get the metadata in the form of field array using getFields() or getDeclaredFields() methods as below:
    Field[]  guru99Field1= guru99ClassObjVar .getFields();
    Field[]  guru99Fiel2= guru99ClassObjVar .getDeclaredFields();

getFields() method returns metadata of the public variable from the specified class as well as from its super class.

getDeclaredFields() method returns metadata of the all the variables from the specified class only.

  1. Get the name of the variables using "public String getName()" method.
  2. Get the datatype of the variables using "public Class getType()" method.
  3. Get the value of the variable using "public xxx get (Field)" method.

    Here, xxx could be a byte or short of any type of value we want to fetch.

  4. Get the access modifiers of the variables using getModifier() and Modifier.toString(int i) methods.
  • Here, we are writing a class to get the metadata of the variables present in the class Guru99VariableMetaData .class:

    Java Reflection API - Tutorial

  1. Created class object for Guru99VariableMetaData.class
  2. Got all the metadata of the variables in a Field array
  3. Printed all the variable names in the class Guru99VariableMetaData.class
  4. Printed all the data types of the variables in the class Guru99VariableMetaData.class
  5. Printed all the access modifiers of the variables in the class Guru99VariableMetaData.class
  6. Printed values of all the variables in Printed all the data types of the variables in the class Guru99VariableMetaData.class

Java Reflection API - TutorialJava Reflection API - Tutorial

Java Reflection Example

Following examples shows how to get metadata of a method:
  • Here, we are creating a class named Guru99MethodMetaData .class with some methods

Java Reflection API - Tutorial

package guru;		
import java.sql.SQLException;		
public class Guru99MethodMetaData {   				

	public void guru99Add(int firstElement, int secondElement , String result) 									
    throws ClassNotFoundException, ClassCastException{			
          System.out.println("Demo method for Reflextion  API");					
    }	
    public String guru99Search(String searchString) 			
    throws ArithmeticException, InterruptedException{			
        System.out.println("Demo method for Reflection API");					
		return null;					
    }	
	public void guru99Delete(String deleteString) 					
	throws SQLException{			
	    System.out.println("Demo method for Reflection API");					
    }	
}	
  • Steps to get the metadata about the methods in the above class :
  1. Create the class object of the above class i.e. Guru99MethodMetaData.class as below:
    Guru99MethodMetaData  guru99ClassVar  = new Guru99MethodMetaData  ();
    Class  guru99ClassObjVar  = guru99ClassVar.getClass();
  2. Get method information in a Method array using getMethods() and getDeclaredMethods() method as below:
    Method[]  guru99 Method 1= guru99ClassObjVar .get Methods();
    Method []  guru99 Method 2= guru99ClassObjVar .getDeclared Method s();

    getMethods() method returns metadata of the public methods from the specified class as well as from its super class.

    getDeclaredMethods() method returns metadata of the all the methods from the specified class only.

  3. Get the name of the method using getName() method.
  4. Get the return type of the method using getReturnType() method.
  5. Get access modifiers of the methods using getModifiers() and Modifiers.toString(int i) methods.
  6. Get method parameter types using getParameterTypes() method which returns a class array.
  7. Get thrown exception using getExceptionTypes() method which returns a class array.
  • Here, we are writing a class to get the metadata of the methods present in the class Guru99MethodMetaData.class:

Java Reflection API - Tutorial

  1. Created class object for Guru99MethodMetaData.class
  2. Got all the metadata of all the methods in a Method array
  3. Printed all the method names present in the class Guru99MethodMetaData.class
  4. Printed return types of the methods in the class Guru99MethodMetaData.class
  5. Printed all the access modifiers of the methods in the class Guru99MethodMetaData.class
  6. Printed parameter types of the methods in Guru99MethodMetaData.class
  7. Printed exceptions are thrown by methods in Guru99MethodMetaData.class

    Java Reflection API - Tutorial

Java Reflection API - Tutorial

Java Reflection Example

Following examples shows how to get metadata of constructors:
  • Here, we are creating a class named Guru99Constructor.class with different constructors:

    Java Reflection API - Tutorial

package guru;		

import java.rmi.RemoteException;		
import java.sql.SQLException;		

public class Guru99Constructor {				

	public Guru99Constructor(int no) throws ClassCastException ,ArithmeticException{  }							
	public Guru99Constructor(int no, String name) throws RemoteException ,SQLException{  }							
	public Guru99Constructor(int no, String name, String address) throws InterruptedException{  }							
}
  • Here, we are writing a class to get the metadata of the constructors present in the class Guru99Constructor.class:

Java Reflection API - Tutorial

  1. Created class object for Guru99Constructor.class
  2. Got all the metadata of all the constructors in a Constructor array
  3. Printed all the constructors names present in the class Guru99Constructor.class
  4. Printed all the access modifiers of the constructors in the class Guru99Constructor.class
  5. Printed parameter types of the constructors in Guru99Constructor.class
  6. Printed exceptions are thrown by constructors in Guru99Constructor.class

Java Reflection API - Tutorial

Java Reflection API - Tutorial

Summary:

  • Reflection programming in java helps in retrieving and modifying information about Classes and Class members such variable, methods, constructors.
  • Reflection API in Java can be implemented using classes in java.lang.reflect package and methods of java.lang.Class class.
  • Some commonly used methods of java.lang.Class class are getName (), getSuperclass (), getInterfaces (), getModifiers () etc.
  • Some commonly used classes in java.lang.reflect package are Field, Method, Constructor, Modifier, etc.
  • Reflection API can access private methods and variables of a class which could be a security threat.
  • Reflection API is a powerful capability provided by Java, but it comes with some overheads such as slower performance, security vulnerability, and permission issue. Hence, reflection API should be treated as the last resort to perform an operation.

 

YOU MIGHT LIKE: