Java Reflection Complete Tutorial

Java Reflection Complete Tutorial - Learn From Examples

Java Reflection Complete Tutorial – Learn From Examples

 

Reflection is used to analyzing the entire details about a Class during Runtime. Mostly reflection is used for Product development or framework development.

Important packages for Reflection

  • lang.Class
  • lang.reflect
  • lang.reflect.Field
  • lang.reflect.Method
  • lang.reflect.Constructor
  • lang.reflect.Modifier

Consider the class Department

import java.io.Serializable;

public abstract class Department implements Serializable,Cloneable{
    public String empNo = "34";
    private String empName = "34";
    String deptNo = "sdf";
    protected String deptName;
    public String getEmpNo() {
        return empNo;
    }
    public void setEmpNo(String empNo) {
        this.empNo = empNo;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public String getDeptNo() {
        return deptNo;
    }
    public void setDeptNo(String deptNo) {
        this.deptNo = deptNo;
    }
    public String getDeptName() {
        return deptName;
    }
    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
    public String getEmployeeDetails(String name, String empId, String address, int j) throws Exception,IndexOutOfBoundsException{
        return name+empId+address;
    }
} 

 

Let’s see the diagrammatic representation of class details which we can access through Reflection API.

Java Reflection

Java Reflection

Reflection API to get details about Class, SuperClass and Interfaces

Method Name Description
String getName() To get the name of a class
Class getSuperClass() To get the Super Class object.
Class[] getInterfaces() To get Array of Interface Object
int getModifiers() Returns int which will be used to get Modifier details
Static String Modifier.toString(int) To get the modifier.

 

Now we will see all the internal details of a entire class using Reflection API.

import java.lang.reflect.Modifier;

public class ReflectionImplementation {

 public static void main(String[] args) throws ClassNotFoundException {
 // TODO Auto-generated method stub

 // To get Details about Class
 Class cls = Class.forName("Department");
 System.out.println("Name of the Class is : " + cls.getName());
 System.out.println("Name of the Class is : " + cls.getCanonicalName());
 System.out.println("Name of the Class is : " + cls.getSimpleName());

 //To get Details about SuperClass
 Class superClass = cls.getSuperclass();
 System.out.println("Name of the SuperClass is : " + superClass.getName());
 System.out.println("Name of the SuperClass is : " + superClass.getCanonicalName());
 System.out.println("Name of the SuperClass is : " + superClass.getSimpleName());

 //To get Modifiers about Class
 int modifierValue = cls.getModifiers();
 System.out.println("Name of the Class Modifier is : " + Modifier.toString(modifierValue));

 // To get InterfaceList
 Class interfaceList[] = cls.getInterfaces();
 for(Class c : interfaceList){
      System.out.println("Interface Name is : " + c.getName());
      int val = c.getModifiers();
      System.out.println("Interface Modifier is : " + Modifier.toString(val));
 }
 }

}

Output


Name of the Class is : Department
Name of the Class is : Department
Name of the Class is : Department
Name of the SuperClass is : java.lang.Object
Name of the SuperClass is : java.lang.Object
Name of the SuperClass is : Object
Name of the Class Modifier is : public abstract
Interface Name is : java.io.Serializable
Interface Modifier is : public abstract interface
Interface Name is : java.lang.Cloneable
Interface Modifier is : public abstract interface

Field

To know about the internal details of a variable like data type of a variable or access specifiers etc., we have Field API.  Now we will see some of the important methods of Field API.

Method Name Description
Field[] getFields() To get all the public fields also all the public fields of its Super Class.
Field[] getDeclaredFields() To get all the fields irrespective of its access specifiers, but not from any of its super class.
String getName() To get the name of a Variable
Class getType() To get the Data Type of a variable.
xxx get(Field) To get the value of a variable. xxx can be any dataType
int getModifiers() Returns int which will be used to get Modifier details of a variable.
Static String Modifier.toString(int) To get the modifier of a variable.

Employee.java

public class Employee {
    public String empName;
    private double empSalary;
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public double getEmpSalary() {
        return empSalary;
    }
    public void setEmpSalary(double empSalary) {
        this.empSalary = empSalary;
    }
}

Manager.java

public class Manager extends Employee {
    public String empNo = "EMP001";
    String deptNo = "ACCOUNTS";
    protected String deptName;
    private String password;
    
    public String getEmpNo() {
        return empNo;
    }
    public void setEmpNo(String empNo) {
        this.empNo = empNo;
    }
    public String getDeptNo() {
        return deptNo;
    }
    public void setDeptNo(String deptNo) {
        this.deptNo = deptNo;
    }
    public String getDeptName() {
        return deptName;
    }
    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

ReflectionFieldImplementation.java

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ReflectionFieldImplementation {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Manager manager = new Manager();
        Class clz =  manager.getClass();
        
        /*
         * getFields get only public access specifier variables from its
           Current class and form its super class.         
        */
        System.out.println("getFields()");
        System.out.println("---------------------------------------");
        Field[] fields = clz.getFields();
        for(Field field : fields){
            System.out.println("Variable Name is :" +field.getName());
            System.out.println("Variable Type is :" +field.getType().getName());
            int value = field.getModifiers();
            System.out.println("Variable Access Modifier is :" +Modifier.toString(value));
            Object values;
            try {
                values = field.get(manager);
                if(null!=values){
                    System.out.println("Variable Value is :"+values.toString());
                }else{
                    System.out.println("Variable Value is :"+values);
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                // TODO Auto-generated catch block
                System.out.println("PRIVATE VARIBALE CANNOT BE ACCESSED!!!!!!!!!!!!!!!!!!!");
                //e.printStackTrace();
            }
            System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        }
        System.out.println("---------------------------------------");
        System.out.println("\n \n \n \n \n \n \n");
        System.out.println("getDeclaredFields()");
        System.out.println("---------------------------------------");
        /* getDeclaredFields get all access specifier variables but not from
        its superclass*/
        Field[] declaredFields = clz.getDeclaredFields();
        for(Field field : declaredFields){
            System.out.println("Variable Name is :" +field.getName());
            System.out.println("Variable Type is :" +field.getType().getName());
            int value = field.getModifiers();
            System.out.println("Variable Access Modifier is :" +Modifier.toString(value));

            Object values;
            try {
                values = field.get(manager);
                if(null!=values){
                    System.out.println("Variable Value is :"+values.toString());
                }else{
                    System.out.println("Variable Value is :"+values);
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                // TODO Auto-generated catch block
                System.out.println("PRIVATE VARIBALE CANNOT BE ACCESSED!!!!!!!!!!!!!!!!!!!");
                //e.printStackTrace();
            }
            System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        }
    }

}

Output

getFields()
---------------------------------------
Variable Name is :empNo
Variable Type is :java.lang.String
Variable Access Modifier is :public
Variable Value is :EMP001
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Variable Name is :empName
Variable Type is :java.lang.String
Variable Access Modifier is :public
Variable Value is :null
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
---------------------------------------

 
 
 
 
 
 

getDeclaredFields()
---------------------------------------
Variable Name is :empNo
Variable Type is :java.lang.String
Variable Access Modifier is :public
Variable Value is :EMP001
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Variable Name is :deptNo
Variable Type is :java.lang.String
Variable Access Modifier is :
Variable Value is :ACCOUNTS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Variable Name is :deptName
Variable Type is :java.lang.String
Variable Access Modifier is :protected
Variable Value is :null
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Variable Name is :password
Variable Type is :java.lang.String
Variable Access Modifier is :private
PRIVATE VARIBALE CANNOT BE ACCESSED!!!!!!!!!!!!!!!!!!!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When we see the output we could able to see output for both getFields and getDeclaredFields.

Note:

1. For Default access specifiers, getType() is printing empty
2. IllegalAccessException will be thrown when we try to access private variables.

 Method

To know about the internal details of a method like return type of a method or access specifiers, arguments, exceptions etc., we have a API called Method.  Now we will see some of the important methods of Method API.

Method Name Description
Method[] getMethods() To get all the public methods details of a class also to get all the public methods details of its Super Class.
Method[] getMethod(String methodName, Class[] parameterTypes) To get the public method details of a class.
Method[] getDeclaredMethods() To get all the methods details irrespective of its access specifiers, but not from any of its super class.
String getName() To get the name of a Method
Class getReturnType() To get the return type of a Method.
int getModifiers() Returns int which will be used to get Modifier details of a variable.
Static String Modifier.toString(int) To get the modifier of a variable.
Class[] getParameterTypes() To get the data type of the argument which has been passed
Class[] getExceptionTypes() To get the details about the exception which has been thrown.

 Student.java

public class Student {
    private int addStudent(int rollNo, String studentName, String className,
            String sectionName)throws ClassCastException, ClassNotFoundException, NumberFormatException
    {
        return 0;
    }
    private int deleteStudent(int rollNo,  String className,
            String sectionName) throws NullPointerException{
        return 0;
    }
    public String searchStudent(int rollNo) throws ArithmeticException{
        return null;
    }
}

ReflectionMethodImplementation.java

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class ReflectionMethodImplementation {

    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
        // TODO Auto-generated method stub
        Class cls = Student.class;
        
        //getDeclared Methods
        Method[] declaredMethods = cls.getDeclaredMethods();
        for(Method method : declaredMethods){
            System.out.println("Method Name is : "+method.getName());
            
            Class returnType = method.getReturnType();
            System.out.println("Return Type is :" + returnType.getName());

            int val = method.getModifiers();
            System.out.println("Modifier of a field is : " +Modifier.toString(val));
            
            Class[] parameterTypes =  method.getParameterTypes();
            for(Class parameterType : parameterTypes){
                System.out.println("Parameter Types : " + parameterType.getName());
            }
            
            Class[] exceptionTypes = method.getExceptionTypes();
            for(Class exceptionType : exceptionTypes){
                System.out.println("Exception Types : " + exceptionType.getName());
            }
            System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
         }
        
        
        System.out.println("--------------------------------------------");
        
        
        //getMethods
        Method[] methods = cls.getMethods();
        for(Method method : methods){
            System.out.println("Method Name is : "+method.getName());
            
            Class returnType = method.getReturnType();
            System.out.println("Return Type is :" + returnType.getName());

            int val = method.getModifiers();
            System.out.println("Modifier of a field is : " +Modifier.toString(val));
            
            Class[] parameterTypes =  method.getParameterTypes();
            for(Class parameterType : parameterTypes){
                System.out.println("Parameter Types : " + parameterType.getName());
            }
            
            Class[] exceptionTypes = method.getExceptionTypes();
            for(Class exceptionType : exceptionTypes){
                System.out.println("Exception Types : " + exceptionType.getName());
            }
            System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
         }
        
        
        System.out.println("--------------------------------------------");
        //getMethod
        
        try {
            Method singleMethod = cls.getMethod("searchStudent", new Class[]{int.class});
            System.out.println("Method Name is : "+singleMethod.getName());
            
            Class returnType = singleMethod.getReturnType();
            System.out.println("Return Type is :" + returnType.getName());

            int val = singleMethod.getModifiers();
            System.out.println("Modifier of a field is : " +Modifier.toString(val));
            
            Class[] parameterTypes =  singleMethod.getParameterTypes();
            for(Class parameterType : parameterTypes){
                System.out.println("Parameter Types : " + parameterType.getName());
            }
            
            Class[] exceptionTypes = singleMethod.getExceptionTypes();
            for(Class exceptionType : exceptionTypes){
                System.out.println("Exception Types : " + exceptionType.getName());
            }
            System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
            
        } catch (NoSuchMethodException | SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Output

Method Name is : searchStudent
Return Type is :java.lang.String
Modifier of a field is : public
Parameter Types : int
Exception Types : java.lang.ArithmeticException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Method Name is : deleteStudent
Return Type is :int
Modifier of a field is : private
Parameter Types : int
Parameter Types : java.lang.String
Parameter Types : java.lang.String
Exception Types : java.lang.NullPointerException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Method Name is : addStudent
Return Type is :int
Modifier of a field is : private
Parameter Types : int
Parameter Types : java.lang.String
Parameter Types : java.lang.String
Parameter Types : java.lang.String
Exception Types : java.lang.ClassCastException
Exception Types : java.lang.ClassNotFoundException
Exception Types : java.lang.NumberFormatException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--------------------------------------------
Method Name is : searchStudent
Return Type is :java.lang.String
Modifier of a field is : public
Parameter Types : int
Exception Types : java.lang.ArithmeticException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Method Name is : wait
Return Type is :void
Modifier of a field is : public final
Parameter Types : long
Parameter Types : int
Exception Types : java.lang.InterruptedException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Method Name is : wait
Return Type is :void
Modifier of a field is : public final native
Parameter Types : long
Exception Types : java.lang.InterruptedException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Method Name is : wait
Return Type is :void
Modifier of a field is : public final
Exception Types : java.lang.InterruptedException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Method Name is : equals
Return Type is :boolean
Modifier of a field is : public
Parameter Types : java.lang.Object
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Method Name is : toString
Return Type is :java.lang.String
Modifier of a field is : public
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Method Name is : hashCode
Return Type is :int
Modifier of a field is : public native
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Method Name is : getClass
Return Type is :java.lang.Class
Modifier of a field is : public final native
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Method Name is : notify
Return Type is :void
Modifier of a field is : public final native
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Method Name is : notifyAll
Return Type is :void
Modifier of a field is : public final native
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--------------------------------------------
Method Name is : searchStudent
Return Type is :java.lang.String
Modifier of a field is : public
Parameter Types : int
Exception Types : java.lang.ArithmeticException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Note:

1. Using getMethods(), we can able to access all public methods of the current class as well as its super class, since we don’t extends any super class, object class method details are printed now
2. Using getMethod(), we can able to access only public method, if we try to access non public methods, then NoSuchMethodException will be thrown

Constructor

To know about the internal details of a constructor like access specifiers, arguments, exceptions etc., we have a API called Constructor.  Now we will see some of the important methods of Method API.

Method Name Description
Constructor[] getConstructor() To get all the public constructor details of a class also to get all the public constructor  details of its Super Class.
Constructor[] getDeclaredConstructorMethod(Class[] parameterTypes) To get the public constructor details of a class.
Constructor[] getDeclaredConstructor() To get all the constructor details irrespective of its access specifiers, but not from any of its super class.

Student.java


public class Student {
    
    private String studentName;
    private String studentNo;
    
    private Student()throws ClassCastException, ClassNotFoundException, NumberFormatException{
        
    }
    
    public Student(String studentName, String studentNo)throws ArithmeticException{
        this.studentName = studentName;
        this.studentNo = studentNo;
    }
}

ReflectionConstructorImplementation.java

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;

public class ReflectionConstructorImplementation {

    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
        // TODO Auto-generated method stub
        Class cls = Student.class;
        
        System.out.println("Get Declared Constructor");
        //getDeclared Methods
        Constructor[] declaredConstructor = cls.getDeclaredConstructors();
        for(Constructor constructor : declaredConstructor){
            System.out.println("Constructor Name is : "+constructor.getName());
            
            int val = constructor.getModifiers();
            System.out.println("Modifier of a Constructor is : " +Modifier.toString(val));
            
            Class[] parameterTypes =  constructor.getParameterTypes();
            for(Class parameterType : parameterTypes){
                System.out.println("Parameter Types : " + parameterType.getName());
            }
            
            Class[] exceptionTypes = constructor.getExceptionTypes();
            for(Class exceptionType : exceptionTypes){
                System.out.println("Exception Types : " + exceptionType.getName());
            }
            System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
         }
        
        
        System.out.println("--------------------------------------------");
        
        System.out.println("Get Constructor");
        //getMethods
        Constructor[] constructors = cls.getConstructors();
        for(Constructor constructor : constructors){
            System.out.println("Constructor Name is : "+constructor.getName());
            

            int val = constructor.getModifiers();
            System.out.println("Modifier of a constructor is : " +Modifier.toString(val));
            
            Class[] parameterTypes =  constructor.getParameterTypes();
            for(Class parameterType : parameterTypes){
                System.out.println("Parameter Types : " + parameterType.getName());
            }
            
            Class[] exceptionTypes = constructor.getExceptionTypes();
            for(Class exceptionType : exceptionTypes){
                System.out.println("Exception Types : " + exceptionType.getName());
            }
            System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
         }
        
        
        System.out.println("--------------------------------------------");
        System.out.println("Get Single Constructor");
        //getMethod
        
        try {
            Constructor singleConstructor = cls.getConstructor( new Class[]{String.class,String.class});
            System.out.println("Constructor Name is : "+singleConstructor.getName());
            
            int val = singleConstructor.getModifiers();
            System.out.println("Modifier of a Constructor is : " +Modifier.toString(val));
            
            Class[] parameterTypes =  singleConstructor.getParameterTypes();
            for(Class parameterType : parameterTypes){
                System.out.println("Parameter Types : " + parameterType.getName());
            }
            
            Class[] exceptionTypes = singleConstructor.getExceptionTypes();
            for(Class exceptionType : exceptionTypes){
                System.out.println("Exception Types : " + exceptionType.getName());
            }
            System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
            
        } catch (NoSuchMethodException | SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Output

Get Declared Constructor
Constructor Name is : Student
Modifier of a Constructor is : private
Exception Types : java.lang.ClassCastException
Exception Types : java.lang.ClassNotFoundException
Exception Types : java.lang.NumberFormatException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Constructor Name is : Student
Modifier of a Constructor is : public
Parameter Types : java.lang.String
Parameter Types : java.lang.String
Exception Types : java.lang.ArithmeticException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--------------------------------------------
Get Constructor
Constructor Name is : Student
Modifier of a constructor is : public
Parameter Types : java.lang.String
Parameter Types : java.lang.String
Exception Types : java.lang.ArithmeticException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--------------------------------------------
Get Single Constructor
Constructor Name is : Student
Modifier of a Constructor is : public
Parameter Types : java.lang.String
Parameter Types : java.lang.String
Exception Types : java.lang.ArithmeticException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Note:

1. Using getConstructors(), we can able to access all public constructor of the current class as well as its super class.
2. Using getConstructor(), we can able to access only public constructor, if we try to access non public constructor, then NoSuchMethodException will be thrown

Leave a comment

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