Java Reflections Part -1

Reflection API : Its a per-defined programming interface provided by JDK, which helps us to find out all the capabilities of a class at runtime.

POC of  Reflection API:

Part 1 consists POC on

1. Reflection on Class
2. Reflections on Methods
3. Reflections on Fields.

Finding out the class information.

Lets create a simple class  with name CompanyClassInformation

 package com.learning.reflections;  
 public class CompanyProfileInformation {  
      private String name;  
      private int age;  
      private String company;  
      public CompanyProfileInformation() {  
           System.out.println("Calling Constructor");  
           this.name = "bharani";  
           this.age = 26;  
           this.company = "EIL";  
           System.out.println(name);  
           System.out.println(age);  
           System.out.println(company);  
      }  
      public CompanyProfileInformation(String name, int age, String company) {  
           System.out.println("Calling Parameterized Constructor");  
           this.name = name;  
           this.age = age;  
           this.company = company;  
           System.out.println(this.name);  
           System.out.println(this.age);  
           System.out.println(this.company);  
      }  
      public void getName() {  
           System.out.println(this.name);  
      }  
      public void getAge() {  
           System.out.println(this.age);  
      }  
      public void getCompany() {  
           System.out.println(this.company);  
      }  
      public void getName(String name) {  
           System.out.println(name);  
      }  
      public void getAge(int age) {  
           System.out.println(age);  
      }  
      public void getCompany(String company) {  
           System.out.println(company);  
      }  
 } 
Lets create one more Class called FindingOutClassInformation, Which tells us the information like Class Name, Class Loaders, Constructors and Invoking default and paramterized constructor through reflections.
 package com.learning.reflections;  
 import java.lang.reflect.Constructor;  
 import java.lang.reflect.InvocationTargetException;  
 public class FindingOutClassInformation {  
      @SuppressWarnings({ "rawtypes", "unchecked" })  
      public static void main(String[] args) {  
           try {  
                Class companyProfileInformation = Class.forName("com.learning.reflections.CompanyProfileInformation");  
                // getName will provide you the Class Name with its Package  
                System.out.println(companyProfileInformation.getName());  
                // getName will provide you the Class Name without the package  
                System.out.println("*****************************");  
                System.out.println(companyProfileInformation.getSimpleName());  
                // getClassLoader will provide you the information about the  
                // ClassLoader which loads the class in the JVM.  
                System.out.println("*****************************");  
                System.out.println(companyProfileInformation.getClassLoader());  
                // provides you the information about Constructors  
                System.out.println("*****************************");  
                Constructor[] companyProfileInformationDeclaredConstructors = companyProfileInformation  
                          .getDeclaredConstructors();  
                for (Constructor constructor : companyProfileInformationDeclaredConstructors) {  
                     System.out.println(constructor.getName());  
                }  
                System.out.println("*****************************");  
                Constructor[] companyProfileInformationConstructors = companyProfileInformation.getConstructors();  
                for (Constructor constructor : companyProfileInformationConstructors) {  
                     System.out.println(constructor.getName());  
                }  
                // Invoking a parameterized Constructor  
                Constructor companyProfileInformationParameterizedConstructor = companyProfileInformation  
                          .getConstructor(String.class, int.class, String.class);  
                CompanyProfileInformation paramterizedobject = (CompanyProfileInformation) companyProfileInformationParameterizedConstructor  
                          .newInstance("Bharani", 27, "EGIL");  
                System.out.println("*****************************");  
                // Invoking default Constructor  
                Constructor companyProfileInformationdefaultConstructor = companyProfileInformation.getConstructor();  
                CompanyProfileInformation defaultobject = (CompanyProfileInformation) companyProfileInformationdefaultConstructor  
                          .newInstance();  
           } catch (ClassNotFoundException e) {  
                e.printStackTrace();  
           } catch (NoSuchMethodException e) {  
                e.printStackTrace();  
           } catch (SecurityException e) {  
                e.printStackTrace();  
           } catch (InstantiationException e) {  
                e.printStackTrace();  
           } catch (IllegalAccessException e) {  
                e.printStackTrace();  
           } catch (IllegalArgumentException e) {  
                e.printStackTrace();  
           } catch (InvocationTargetException e) {  
                e.printStackTrace();  
           }  
      }  
 }  
output:
 com.learning.reflections.CompanyProfileInformation  
 *****************************  
 CompanyProfileInformation  
 *****************************  
 sun.misc.Launcher$AppClassLoader@3301f287  
 *****************************  
 com.learning.reflections.CompanyProfileInformation  
 com.learning.reflections.CompanyProfileInformation  
 *****************************  
 com.learning.reflections.CompanyProfileInformation  
 com.learning.reflections.CompanyProfileInformation  
 Calling Parameterized Constructor  
 Bharani  
 27  
 EGIL
 *****************************  
 Calling Constructor  
 bharani  
 26  
 EIL

Finding the information about the methods,declared Methods and invoking methods of a Class 

Lets create one more Class with Name  FindingOutTheMethodsOftheClass which provides us the information of methods of CompanyClassInformation through Reflections.

 package com.learning.reflections;  
 import java.lang.reflect.InvocationTargetException;  
 import java.lang.reflect.Method;  
 import java.util.ArrayList;  
 import java.util.List;  
 public class FindingOutTheMethodsOftheClass {  
      @SuppressWarnings({ "rawtypes", "unchecked" })  
      public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,  
                IllegalArgumentException, InvocationTargetException, InstantiationException {  
           try {  
                // This will create a Class Object  
                Class complayProfileInformation = Class.forName("com.learning.reflections.CompanyProfileInformation");  
                // getMethods will return you the methods used in your current class  
                // as well as its super class.  
                // ***************************************************************  
                // complayProfileInformation Super class is Object, so the methods  
                // of Object class is also visible.  
                Method[] methods = complayProfileInformation.getMethods();  
                for (Method m : methods) {  
                     System.out.println(m.getName());  
                }  
                System.out.println("************************************************************************");  
                // getDeclaredMethods will return you the methods which are declared  
                // in the current class  
                Method[] declaredMethods = complayProfileInformation.getDeclaredMethods();  
                for (Method declaredm : declaredMethods) {  
                     System.out.println(declaredm.getName());  
                }  
                System.out.println("************************************************************************");  
                CompanyProfileInformation cpi = (CompanyProfileInformation) complayProfileInformation.newInstance();  
                // Invoking Methods through Reflections.  
                List<String> listMethodName = new ArrayList<>();  
                listMethodName.add("getName");  
                listMethodName.add("getAge");  
                listMethodName.add("getCompany");  
                for (String methodname : listMethodName) {  
                     switch (methodname) {  
                     case "getName":  
                          System.out.println("************************************************************************");  
                          Method getNamewithParameters = complayProfileInformation.getDeclaredMethod(methodname);  
                          getNamewithParameters.invoke(cpi);  
                          Method getNameWithoutParameters = complayProfileInformation.getDeclaredMethod(methodname,  
                                    String.class);  
                          getNameWithoutParameters.invoke(cpi, "Bharani Ravi Kanth R");  
                          System.out.println("************************************************************************");  
                          break;  
                     case "getAge":  
                          System.out.println("************************************************************************");  
                          Method getagewithParameters = complayProfileInformation.getDeclaredMethod(methodname);  
                          getagewithParameters.invoke(cpi);  
                          Method getageWithoutParameters = complayProfileInformation.getDeclaredMethod(methodname, int.class);  
                          getageWithoutParameters.invoke(cpi, 32);  
                          System.out.println("************************************************************************");  
                          break;  
                     case "getCompany":  
                          System.out.println("************************************************************************");  
                          Method getCompanywithParameters = complayProfileInformation.getDeclaredMethod(methodname);  
                          getCompanywithParameters.invoke(cpi);  
                          Method getCompanyWithoutParameters = complayProfileInformation.getDeclaredMethod(methodname,  
                                    String.class);  
                          getCompanyWithoutParameters.invoke(cpi, "BHARANIRAVIKANTHSOFT");  
                          System.out.println("************************************************************************");  
                          break;  
                     default:  
                          System.err.println("No Such Method available");  
                          break;  
                     }  
                }  
           } catch (ClassNotFoundException e) {  
                System.err.println(e.getMessage());  
           }  
      }  
 }  
output:
 getName  
 getName  
 getAge  
 getAge  
 getCompany  
 getCompany  
 wait  
 wait  
 wait  
 equals  
 toString  
 hashCode  
 getClass  
 notify  
 notifyAll  
 ************************************************************************  
 getName  
 getName  
 getAge  
 getAge  
 getCompany  
 getCompany  
 ************************************************************************  
 Calling Constructor  
 bharani  
 26  
 EIL
 ************************************************************************  
 bharani  
 Bharani Ravi Kanth R  
 ************************************************************************  
 ************************************************************************  
 26  
 32  
 ************************************************************************  
 ************************************************************************  
 EIL  
 BHARANIRAVIKANTHSOFT
 ************************************************************************  

Accessing the Private variables of a class. 

Lets create a simple class PrivateMembersClass.Java which has only private and public variables

 package com.learning.reflections;  
 public class PrivateMembersClass {  
      private String empName = "bharani Ravi Kanth";  
      private int empAge = 27;  
      private String empCompany = "EIL";  
      public String mobileNo = "+918778888278";  
      public String designation = "Solution Integrator";  
 }  
Create one more class FindingOutThePrivateAndPublicVariableOfaClass which we use to access the variables of PrivateMembersClass class through reflections.
 package com.learning.reflections;  
 import java.lang.reflect.Field;  
 public class FindingOutThePrivateAndPublicVariableOfaClass {  
      @SuppressWarnings("rawtypes")  
      public static void main(String[] args)  
                throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InstantiationException {  
           Class privateOutThePrivatePublicVariables = Class.forName("com.learning.reflections.PrivateMembersClass");  
           // GetFields will provide only the public Variables  
           Field[] variablesinClass = privateOutThePrivatePublicVariables.getFields();  
           for (Field field : variablesinClass) {  
                System.out.println(field.getName());  
           }  
           System.out.println("**********************************");  
           // GetDeclaredFields will provide you private and public Variables  
           Field[] PrivateandPublicvariablesinClass = privateOutThePrivatePublicVariables.getDeclaredFields();  
           for (Field field : PrivateandPublicvariablesinClass) {  
                System.out.println(field.getName());  
           }  
           System.out.println("**********************************");  
           // GetDeclaredFields accessing the public variables from the class  
           PrivateMembersClass membersClass = (PrivateMembersClass) privateOutThePrivatePublicVariables.newInstance();  
           for (Field field : variablesinClass) {  
                System.out.println(field.getName());  
                System.out.println(field.get(membersClass));  
           }  
           System.out.println("**********************************");  
           // GetDeclaredFields accessing the public and private variables from the  
           // class  
           // you cannot access private variables directly, We need to set the value as true for the  
           // Field method setAccessible  
           for (Field field : PrivateandPublicvariablesinClass) {  
                System.out.println(field.getName());  
                field.setAccessible(true);  
                System.out.println(field.get(membersClass));  
           }  
      }  
 }  
Output:
 mobileNo  
 designation  
 **********************************  
 empName  
 empAge  
 empCompany  
 mobileNo  
 designation  
 **********************************  
 mobileNo  
 +918778888278  
 designation  
 Solution Integrator  
 **********************************  
 empName  
 bharani Ravi Kanth  
 empAge  
 27  
 empCompany  
 EIL
 mobileNo  
 +918778888278  
 designation  
 Solution Integrator  

I am an open source enthusiast. Currently having 6 years of experience and part of Ericsson Global. I am a traveler, Coding manic, Foodie, Gaming Freak and an Amazing Cook.

Share this

Pages
First

7 comments

Write comments