Reflection – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Tue, 12 Jan 2021 11:54:34 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Reflection – Java2Blog https://java2blog.com 32 32 Get and set Fields using reflection in java https://java2blog.com/get-and-set-fields-using-reflection-java/?utm_source=rss&utm_medium=rss&utm_campaign=get-and-set-fields-using-reflection-java https://java2blog.com/get-and-set-fields-using-reflection-java/#respond Fri, 15 May 2020 18:10:47 +0000 https://java2blog.com/?p=9575 In this post, we will see how to get and set fields using reflection in java.

java.lang.reflect.Field can be used to get/set fields(member variables) at runtime using reflection.

Get all fields of the class

All fields of the class can be obtained from the Class object. Here is an example.

Class cl=Employee.class;
Field[] fields = cl.getFields()

Field[] will have all the public fields of the class.

Get particular field of the class

If you already know name of the fields you want to access, you can use cl.getField(String fieldName) to get Field object.

Getting and setting Field value

Field.get() and Field.set() methods can be used get and set value of field respectively.
Let’s understand with the help of example.
Consider a class named Employee which consists of two private fields name and age.

package org.arpit.java2blog;

public class Employee {

    public String name;
    public int age;

    public Employee(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee [name=" + name + ", age=" + age + "]";
    }
}

Create main class named PrivateFieldReflectionMain

package org.arpit.java2blog;

import java.lang.reflect.Field;

public class GetSetFieldReflectionMain {

    public static void main(String[] args) {
        try {
            Employee e=new Employee("John",30);

            Field fieldName = Employee.class.getField("name");

            // Getting field value
            String name=(String) fieldName.get(e);
            System.out.println("Name of Employee:"+name);

            // Setting field value
            fieldName.set(e, "Amit");
            System.out.println("Employee's updated name: "+e.getName());

        } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

When you run above class, you will get below output:
Output:

Name of Employee:John
Employee’s updated name:Amit

Please note that Here parameter to get() and set() should be object of the class to which field belongs.
For example:
In this case, name field belongs to Employee class, we have passed e to get() and set() method of field object.

Getting and setting static Field value

In case, you want to get and set static field, then you need to pass null while using get() and set() method of Field.
For example:

public class Employee {

    public static String name;

then you can get and set field as below:

// Getting field value
String name=(String) fieldName.get(null);
System.out.println("Name of Employee:"+name);

// Setting field value
fieldName.set(null, "Amit");

That’s all about how to get and set Fields using reflection in java.

]]>
https://java2blog.com/get-and-set-fields-using-reflection-java/feed/ 0
Access private fields and methods using reflection in java https://java2blog.com/access-private-fields-and-methods-using-reflection-java/?utm_source=rss&utm_medium=rss&utm_campaign=access-private-fields-and-methods-using-reflection-java https://java2blog.com/access-private-fields-and-methods-using-reflection-java/#respond Fri, 15 May 2020 18:07:28 +0000 https://java2blog.com/?p=9564 In this post, we will see how to access private fields and methods using reflection in java.
Can you access private fields and methods using reflection?
Yes, you can. It is very easy as well. You just need to call .setAccessible(true) on field or method object which you want to access.

Access private field

Class.getDeclaredField(String fieldName) or Class.getDeclaredFields() can be used to get private fields.

💡 Did you know?

Class.getField(String fieldName) and Class.getFields() return public fields only, so you won’t be able to get private fields with them

Let’s see this with the help of example:
Consider a class named Employee which consists of two private fields name and age.

package org.arpit.java2blog;

public class Employee {

    private String name;
    private int age;

    public Employee(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee [name=" + name + ", age=" + age + "]";
    }
}

Create main class named PrivateFieldReflectionMain

package org.arpit.java2blog;

import java.lang.reflect.Field;

public class PrivateFieldReflectionMain {

    public static void main(String[] args) {
        try {
            Employee e=new Employee("John",30);

            Field privateField = Employee.class.getDeclaredField("name");

            privateField.setAccessible(true);

            String name=(String) privateField.get(e);
            System.out.println("Name of Employee:"+name);
        } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

When you run above class, you will get below output:
Output:

Name of Employee:John

As you can see, we are able to access private field name using reflection.

Access private method

If you want to invoke any method using reflection, you can go through invoke method using reflection.

Class.getDeclaredMethod(String methodName,Class<?>... parameterTypes) or Class.getDeclaredMethods() can be used to get private methods.

💡 Did you know?

Class.getMethod(String methodName,Class... parameterTypes) and Class.getMethods() return public methods only, so you won’t be able to get private methods with them

Let’s see this with the help of example:
We will access Employee‘s private method getAge() using reflection.

Create main class named

package org.arpit.java2blog;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class PrivateMethodReflectionMain {

    public static void main(String[] args) {
        try {
            Employee e=new Employee("Martin",33);

            Method privateMethod = Employee.class.getDeclaredMethod("getAge",null);

            privateMethod.setAccessible(true);

            int age=(int) privateMethod.invoke(e);
            System.out.println("Age of Employee: "+age);
        } catch (SecurityException | IllegalArgumentException | IllegalAccessException 
                  | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

When you run above class, you will get below output:
Output:

Age of Employee: 33

As you can see, we are able to access private method getAge() using reflection.
That’s about how to access private fields and methods using reflection in java

]]>
https://java2blog.com/access-private-fields-and-methods-using-reflection-java/feed/ 0
Invoke constructor using Reflection in java https://java2blog.com/invoke-constructor-using-reflection-java/?utm_source=rss&utm_medium=rss&utm_campaign=invoke-constructor-using-reflection-java https://java2blog.com/invoke-constructor-using-reflection-java/#respond Fri, 15 May 2020 18:05:52 +0000 https://java2blog.com/?p=9469 In this post, we will see how to invoke constructor using reflection in java.

You can retrieve the constructors of the classes and instantiate object at run time using reflection. java.lang.reflect.Constructor is used to instantiate the objects.

Instantiate Constructor with no parameters

In case, you want to create object using no args constructor at runtime, you can do it as below.

Class cl = Class.forName("org.arpit.java2blog.Color");

// Call no-args constructor
Object newInstance = cl.newInstance();
System.out.println(newInstance);

Here,
Class.forName("org.arpit.java2blog.Color") is used to load the class and get an object of type Class and we can retrieve a lot of information such as constructors, methods, and annotations etc. at run time with Class object.

You need to replace org.arpit.java2blog.Color with classname for which you want to instantiate object at run time.

cl.newInstance() can be used to create object with no-args constructor at run time.

Instantiate Constructor with parameters

In case, you want to instantiate constructor with parameters, you need to retrieve constructor with parameters and then pass parameters to instantiate it.

Class cl = Class.forName("org.arpit.java2blog.Color");

// Call parameterized constructor
Class[] type = { String.class,String.class };

// get parameterized constructor which takes 2 Strings as parameters
Constructor cons = cl.getConstructor(type);
// String arguments
Object[] obj = { "Red","#FF0000"};
Object newInstancePC = cons.newInstance(obj);
  • You need to pass Class[] to getConstructor() method and retrieve the instance of java.lang.reflect.Constructor from cl.
  • Pass Object[] to cons.newInstance to construct object with passed parameters.

You can also get Parameters types with cons.getParameterTypes()

Class[] parameterTypes= cons.getParameterTypes();

Let’s see this with an example.
Consider a class named Color which has two attributes name and htmlCode.

package org.arpit.java2blog;

public class Color {

    String name;
    String htmlCode;

    public Color(String name, String htmlCode) {
        super();
        this.name = name;
        this.htmlCode = htmlCode;
    }

    public Color() {
        name = "black";
        htmlCode = "#000000";
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getHtmlCode() {
        return htmlCode;
    }

    public void setHtmlCode(String htmlCode) {
        this.htmlCode = htmlCode;
    }

    @Override
    public String toString() {
        return "Color [name:" + name + " HtmlCode:" + htmlCode + "]";
    }
}

Create main class named ConstuctorReflectionMain

package org.arpit.java2blog;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ConstuctorReflectionMain {

    public static void main(String[] args) {

        try {
            Class cl = Class.forName("org.arpit.java2blog.Color");

            System.out.println("====================");
            System.out.println("Calling default constructor");
            System.out.println("====================");
            // Call default constructor
            Object newInstance = cl.newInstance();
            System.out.println(newInstance);

            System.out.println("====================");
            System.out.println("Calling parameterized constructor");
            System.out.println("====================");
            Class[] type = { String.class,String.class };

            // get parameterized constructor which takes 2 Strings as parameters
            Constructor cons = cl.getConstructor(type);
            // String arguments
            Object[] obj = { "Red","#FF0000"};
            Object newInstancePCObj = cons.newInstance(obj);

            // cast it to required type
            Color color=(Color) newInstancePCObj;
            System.out.println(color);

        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException 
                     | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        } 
    }
}

When you run above program, you will get below output:
Output:

====================
Calling default constructor
====================
Color [name:black HtmlCode:#000000] ====================
Calling parameterized constructor
====================
Color [name:Red HtmlCode:#FF0000]

As you can see, we are able to instantiate object using java.lang.reflect.Constructor at run time using reflection.

Constructor parameters for primitive types

In case, you have constructor parameters with primitive types, you can use .class suffix with that.
For example:
If the parameter type is of int, then you can use int.class while getting constructor of that type.

Let’s understand with the help of example:
Consider a class Employee with attributes: name and age.

package org.arpit.java2blog;

public class Employee {

    String name;
    int age;

    public Employee(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee [name=" + name + ", age=" + age + "]";
    }
}

Create main class named ConstructorParameterPrimMain

package org.arpit.java2blog;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ConstructorParameterPrimMain {

public static void main(String[] args) {

        try {
            Class cl = Class.forName("org.arpit.java2blog.Employee");

            Class[] type = { String.class,int.class };

            // get parameterized constructor which takes 2 Strings as parameters
            Constructor cons = cl.getConstructor(type);
            // String arguments
            Object[] obj = { "Arpit",28};
            Object newInstanceObj = cons.newInstance(obj);

            // cast it to required type
            Employee emp=(Employee) newInstanceObj;
            System.out.println(emp);

        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException 
                     | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        } 
    }

}

When you run above program, you will get below output:
Output:

Employee [name=Arpit, age=28]

You can also pass Integer.Type instead of int.class.

Class[] type = { String.class,Integer.Type };

Conclusion

You have learnt about how to invoke constructor and instantiate objects at runtime using reflection. We have also seen how to handle primitive type parameters while getting constructor from class.
That’s all about how to invoke constructor using Reflection in java.

]]>
https://java2blog.com/invoke-constructor-using-reflection-java/feed/ 0
Invoke Getters And Setters Using Reflection in java https://java2blog.com/invoke-getters-setters-using-reflection-java/?utm_source=rss&utm_medium=rss&utm_campaign=invoke-getters-setters-using-reflection-java https://java2blog.com/invoke-getters-setters-using-reflection-java/#comments Wed, 24 Oct 2018 17:43:44 +0000 https://java2blog.com/?p=6748 In this post, we will see how to call getters and setters using reflection in java. We have already seen how to invoke method using reflection in java.

There are two ways to invoke getter and setter using reflection in java.


Using PropertyDescriptor

You can use PropertyDescriptor to call getters and setters using reflection.
Getter: call getReadMethod() on PropertyDescriptor
Setter: Call getWriteMethod() on PropertyDescriptor.

Let’s understand with simple example.
We will create an object of employee object and then will invoke getters and setters on that.
Create Employee.java as below.

package org.arpit.java2blog;

public class Employee {
    String name;
    int age;

    public Employee()
    {

    }
    public Employee(String name, int age) {
        this.name=name;
        this.age=age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

Create InvokeGetterSetterMain to call getters and setters on employee object.

package org.arpit.java2blog;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class InvokeGetterSetterMain {
    public static void main(String[] args)
    {
        InvokeGetterSetterMain igsm=new InvokeGetterSetterMain();
        Employee emp1=new Employee();
        igsm.invokeSetter(emp1, "name", "John");
        igsm.invokeSetter(emp1, "age", 25);

        igsm.invokeGetter(emp1, "name");
        igsm.invokeGetter(emp1, "age");

    }

    public void invokeSetter(Object obj, String propertyName, Object variableValue)
    {
        PropertyDescriptor pd;
        try {
            pd = new PropertyDescriptor(propertyName, obj.getClass());
            Method setter = pd.getWriteMethod();
            try {
                setter.invoke(obj,variableValue);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }

    }

    public void invokeGetter(Object obj, String variableName)
    {
        try {
            PropertyDescriptor pd = new PropertyDescriptor(variableName, obj.getClass());
            Method getter = pd.getReadMethod();
            Object f = getter.invoke(obj);
            System.out.println(f);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | IntrospectionException e) {
            e.printStackTrace();
        }
    }
}

When you run above program, you will get below output:

John
25

As you can see, we are able to call getters and setters using reflection.


Using Class’s getDeclaredMethods

We can search for getter and setter of any attributes and invoke it.
Here is simple program for the same.

package org.arpit.java2blog;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class InvokeGetterSetterWithMethodsMain {

    public static void main(String[] args) {
        InvokeGetterSetterWithMethodsMain igsm=new InvokeGetterSetterWithMethodsMain();
        Employee emp1=new Employee();

        Method methodName= igsm.getMethod("name",emp1.getClass(),"setter");
        igsm.invokeSetter(emp1, "Martin",methodName);

        Method methodAge= igsm.getMethod("age",emp1.getClass(),"setter");
        igsm.invokeSetter(emp1, 28,methodAge);

        Method methodNameGet= igsm.getMethod("name",emp1.getClass(),"getter");
        igsm.invokeGetter(emp1,methodNameGet);

        Method methodAgeGet= igsm.getMethod("age",emp1.getClass(),"getter");
        igsm.invokeGetter(emp1,methodAgeGet);
    }
    public Method getMethod(String variableName,Class aClass,String getterOrSetter)
    {

        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method method:declaredMethods) {
            if(getterOrSetter.equalsIgnoreCase("getter"))
            {
                if(isGetter(method) && method.getName().toUpperCase().contains(variableName.toUpperCase()))
                {
                    return method;
                }
            }
            if(getterOrSetter.equalsIgnoreCase("setter"))
            {
                if(isSetter(method) && method.getName().toUpperCase().contains(variableName.toUpperCase()))
                {
                    return method;
                }
            }
        }
        return null;
    }
    private static boolean isGetter(Method method){
        // check for getter methods
        if((method.getName().startsWith("get") || method.getName().startsWith("is")) 
                && method.getParameterCount() == 0 && !method.getReturnType().equals(void.class)){
            return true;
        }
        return false;    
    }

    private static boolean isSetter(Method method){
        // check for setter methods
        if(method.getName().startsWith("set") && method.getParameterCount() == 1 
                && method.getReturnType().equals(void.class)){
            return true;
        }
        return false;    
    }

    public void invokeSetter(Object obj,Object variableValue,Method setter)
    {
        try {
            setter.invoke(obj,variableValue);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    public void invokeGetter(Object obj,Method getter)
    {
        try {
            Object f = getter.invoke(obj);
            System.out.println(f);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

When you run above program, you will get below output:

Martin
28

That’s all about how to invoke Getters And Setters Using Reflection in java

]]>
https://java2blog.com/invoke-getters-setters-using-reflection-java/feed/ 2
How to invoke method using reflection in java https://java2blog.com/invoke-method-reflection-java/?utm_source=rss&utm_medium=rss&utm_campaign=invoke-method-reflection-java https://java2blog.com/invoke-method-reflection-java/#respond Sat, 23 Sep 2017 18:06:12 +0000 https://www.java2blog.com/?p=4023 In this post, we will see how to invoke the method using reflection in java.
Let’s understand this with the help of the example.
Create a class named Employee.java. We will invoke this class’s method using reflection.

package org.arpit.java2blog.methodinvocation;

public class Employee {
    String name;
    int age;
    String address; 

    public Employee(String name, int age, String address) {
        super();
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public void printName(String name)
    {
        System.out.println("Name:"+ name);
    }

    protected void printAge(int age)
    {
        System.out.println("Age : "+age);
    }

    private void printAddress(String address)
    {
        System.out.println("Address : "+address);
    }

    public String toString()
    {
        return name+"_"+age+"_"+address;
    }

    public static void printNationality()
    {
        System.out.println("Nationality: Indian");
    }
}

Create a main method named EmployeeReflectionMain.java.

package org.arpit.java2blog.methodinvocation;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class EmployeeReflectionMain {

    public static void main(String[] args) {
            Class cls;

            // For constructor invocation
            Class[] constructorEmp = new Class[] { String.class, int.class ,String.class};
            String name="John";
            int age=20;
            String address="HighStreet";

            Constructor empConst;

            Object[] constArgs = new Object[] { name,age,address};
            try {
                cls = (Class) Class.forName("org.arpit.java2blog.methodinvocation.Employee");
                empConst = cls.getConstructor(constructorEmp);
                Employee e = (Employee) empConst.newInstance(constArgs);

                System.out.println("================================");
                System.out.println("Calling printName method using reflection");
                System.out.println("================================");
                //String parameter
                Class[] paramString = new Class[1];
                paramString[0] = String.class;

                //call the printName method and need to pass string parameter
                Method method = cls.getMethod("printName", paramString);
                method.invoke(e, e.name);

                System.out.println("================================");
                System.out.println("Calling protected printAge method using reflection");
                System.out.println("================================");

                //int parameter
                Class[] paramInt = new Class[1];
                paramInt[0] = Integer.TYPE;

                //call the printAge method and need to pass Integer parameter
                // As printAge is protected, need to call cls.getDeclaredMethod
                method = cls.getDeclaredMethod("printAge", paramInt);
                method.invoke(e, e.age);

                System.out.println("================================");
                System.out.println("Calling toString method using reflection and capturing return value");
                System.out.println("================================");
                //no paramater
                Class noparams[] = {};

                method = cls.getDeclaredMethod("toString", noparams);
                String toStringStr=(String) method.invoke(e, null);
                System.out.println(toStringStr);

                System.out.println("================================");
                System.out.println("Calling static method printNationality using Reflection");
                System.out.println("================================");

                method = cls.getMethod("printNationality", noparams);
                method.invoke(null,null);

                System.out.println("================================");
                System.out.println("Calling private method printAddress using Reflection");
                System.out.println("================================");

                method = cls.getDeclaredMethod("printAddress", paramString);
                method.setAccessible(true);
                method.invoke(e,e.address);

            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException 
                    | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) {
                e.printStackTrace();
            }       
    }
}

When you run above program, you will get below output:

================================
Calling printName method using reflection
================================
Name:John
================================
Calling protected printAge method using reflection
================================
Age : 20
================================
Calling toString method using reflection and capturing return value
================================
John_20_HighStreet
================================
Calling static method printNationality using Reflection
================================
Nationality: Indian
================================
Calling private method printAddress using Reflection
================================
Address : HighStreet

Explanation
You need to first create an object of Class.We will get all the info such as constructors, methods and fields using this cls object.

Class cls = (Class) Class.forName("org.arpit.java2blog.methodinvocation.Employee");

Invoke method without parameters

//no parameter
                Class noparams[] = {};

                method = cls.getDeclaredMethod("toString", noparams);
                String toStringStr=(String) method.invoke(e, null);
                System.out.println(toStringStr);

You need to use getDeclareMethod() to get toString() method and toString() do not have any parameter hence, we will pass empty params.

Invoke method with parameters

//String parameter
                Class[] paramString = new Class[1];
                paramString[0] = String.class;

                //call the printName method and need to pass string parameter
                Method method = cls.getMethod("printName", paramString);
                method.invoke(e, e.name);

As printName() is public method, we can use getMethod() to get method of the object and pass String parameter to printName() method.

Invoke static method using reflection

//no parameter
                Class noparams[] = {};
             method = cls.getMethod("printNationality", noparams);
                method.invoke(null,null);

As you can see, we don’t require any object for static method, we are invoking methods using method.invoke(null,null).

Invoke private method using reflection

//String parameter
                Class[] paramString = new Class[1];
                paramString[0] = String.class;

                 method = cls.getDeclaredMethod("printAddress", paramString);
                method.setAccessible(true);
                method.invoke(e,e.address);

If you want to invoke private method using reflection, you need call method.setAccessible(true) explicitly and then only you can access private method.

]]>
https://java2blog.com/invoke-method-reflection-java/feed/ 0
Java Reflection tutorial https://java2blog.com/java-reflection-tutorial/?utm_source=rss&utm_medium=rss&utm_campaign=java-reflection-tutorial https://java2blog.com/java-reflection-tutorial/#respond Sat, 23 Sep 2017 07:12:34 +0000 http://www.java2blog.com/?p=3348 Introduction

Reflection, as we know from the common term, is an image of yourself or something else you see in a mirror or a mirrored surface. Java, being an object-oriented language draws heavily from real-life examples and so is the Reflection API of Java inspired from real life.

In Java, the process of analyzing, viewing and modifying all the internal attributes, behaviors and capabilities of a class at runtime is called Reflection. Using the concept of Reflection, a programmer can now manipulate all attributes of a class – including its methods, constructors, and fields even at runtime, and even invoke methods of that class and get a complete snapshot of it.

Reflection is heavily used in Java frameworks such as Spring, Hibernate, Junit etc.

The ‘reflect’ package

The core collection of classes and information related to Reflection in Java is encapsulated as the java.lang.reflect package. It contains several interfaces and classes which define methods that are used for reflection of other classes.

Let us have a look at some of the classes within the java.lang.reflect package

Field

This class provides information about the fields present in the class whose reflection is being looked at.

Modifier

This class provides information about the class and other members’ access modifiers of the class being reflected.

Proxy

This class supports the dynamic proxy classes

Method

This class provides information about the methods of the class being reflected and inspected.

Constructor

This class provides information regarding the constructors of the class being reflected and inspected.

Array

This class allows the programmer to dynamically create and manipulate Arrays

Other than these, the java.lang.Class class is one of the most important classes in use for Reflection as the objects of Class can store the actual information of the class that we want to investigate or reflect.

Uses of Reflection in Java

Extensibility

Using the concepts of reflection, a programmer can make use of externally available user-defined classes by creating instances of those extensible objects by using their fully qualified name

Developing IDEs and Class Browsers

IDEs, especially those which are capable of visual development, such as Eclipse or Netbeans, and class browsers can make extensive use of Reflection. Using these, the visual development environments make the information of the classes readily available to the user so that they can write proper code.

Debugging and Testing tools

Debugging requires the ability to view internal details of a class which include its private members.Debugging and Testing tools may use reflection to make systematic invocations to the classes by use of reflection and ensure test case coverage.

Disadvantages of Reflection

Inspite of being an extremely powerful tool, Reflection API and its usage does have a set of disadvantages such as,

Low Performace

The use of reflection API can lead to high performance overhead and lead to lower performance. This is because many functionalities make use of dynamic resolution which prevents to the use of certain Virtual machine optimisations. As it tends to slow down processing, it isn’t recommended for use in sections of code that require high availability and low turnaround.

Security Risk

Reflection API requires cetain security permissions that are not available during execution under a securely managed system. Also, the security permission requirements can pose a threat to code residing in a secure system.

Exposure of Internal Fields and Attributes

Due to the ability of Reflection API to access private members and invoke private functions, the internal details of classes and entities are exposed to the outside world and defeats the purpose of Abstraction in object oriented concepts, which may be seen as a violation of object oriented programming concepts.

Now that we have had an overview of the basic idea of Reflection, let us go through the java.lang.Class class which plays the most significant role in reflection in java.

Java.lang.Class – the gateway to Reflection

The Class is a final class in the java.lang package of Java’s standard library, and extends the Object class which forms the basis of all classes in java. An instance of the class Class is used to represent both classes and interfaces in a Java application which is running. Using an instance of Class, we can view, analyse and modify the attributes of a class while it is running, and can even invoke methods of that class.

Important Methods of java.lang.Class

The Class class has a wide variety of methods that are useful in obtaining a reflection of the class executing and performing a wide range of actions with that class. Some of these methods are:

forName() method:

This method accepts the full qualified name of a class or an interface as an argument and returns an instance of the class associated with the qualifed name, including all its attributes and behaviours.

The syntax for the forName method is as follows:

static Class<?> forName(String className)

Let us see an example of the forName method:

class TestClass{}
class ReflectionTest
{
 public static void main(String args[])
 {
  Class c = null;
try {
    c = Class.forName("TestClass");
} catch (ClassNotFoundException e) {
    System.out.println(e.getMessage());
}
  System.out.println(c.getName());
 }
}

The above code generates the following output:

TestClass

getConstructors() and getDeclaredConstructors() methods:

The getConstructors() method returns an array of the declared public constructors of the invoking object in the form of java.lang.reflect.Constructor objects. The getDeclaredConstructors() method returns all the constructors of the invoking object including non-public members.

The syntax for both getConstructors() and getDeclaredConstructors() are as follows:

Constructor< ?>[] getConstructors();
Constructor< ?>[] getDeclaredConstructors();

Let us see an example of the use of the above methods:

package org.arpit.java2blog;

import java.lang.reflect.Constructor;

class TestClass{
    public TestClass(){}
    protected TestClass(Integer a){}
}

public class ReflectionTest
{
    public static void main(String args[])
    {
        try
        {
            Class c = Class.forName("org.arpit.java2blog.TestClass");
            System.out.println("Using getConstructors()");
            Constructor< TestClass>[] ct = c.getConstructors();
            for(int i=0; i< ct.length; i++)
            { System.out.println(ct[i]); }
            System.out.println("====================");
            System.out.println("Using getDeclaredConstructors()");
            Constructor< TestClass>[] cdt = c.getDeclaredConstructors();
            for(int i=0;i< cdt.length;i++)
            { System.out.println(cdt[i]);}

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

The above code on execution produces the following output:

Using getConstructors()
public org.arpit.java2blog.TestClass()
====================
Using getDeclaredConstructors()
public org.arpit.java2blog.TestClass()
protected org.arpit.java2blog.TestClass(java.lang.Integer)

getMethods() and getDeclaredMethods()

The getMethods() function of java.lang.Class returns an array of java.lang.reflect.Method instances that reflect and return all the public methods of the invoking object. On the other hand, the getDeclaredMethods() function returns only the methods declared by the programmer.

The syntax for both functions are as follows:

Method< ?>[] getMethods();
Method< ?>[] getDeclaredMethods();

Let us see an example of the use of the above methods:

package org.arpit.java2blog;

import java.lang.reflect.Method;

class TestClass {
    public void put() {
    }

    protected int show() {
        return 1;
    }

}

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

        try {
            Class c = Class.forName("org.arpit.java2blog.TestClass");
            Method mr[] = c.getMethods();
            System.out.println("==================");
            System.out.println("Using getMethods()");
            System.out.println("==================");
            for (int i = 0; i < mr.length; i++) {
                System.out.println(mr[i]);
            }
            Method md[] = c.getDeclaredMethods();
            System.out.println("===========================");
            System.out.println("Using getDeclaredMethods()");
            System.out.println("============================");
            for (int i = 0; i < md.length; i++) {
                System.out.println(md[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The above code on execution produces the following result:

==================
Using getMethods()
==================
public void org.arpit.java2blog.TestClass2.put()
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
===========================
Using getDeclaredMethods()
============================
public void org.arpit.java2blog.TestClass2.put()
protected int org.arpit.java2blog.TestClass2.show()

Thus you can see that the getMethods() method returns all the public methods of the object including superclasses, whereas getDeclaredMethods() only returned user-declared methods.

getFields() and getDeclaredFields() methods:

The getFields() methods returns an array consisting of java.lang.Field objects which display all the public attributes of the invoking class or interface. On the other hand, the getDeclaredFields() method returns an array of Field objects which represent all the fields declkared in the invoking class or interface.

The syntax of the methods are as follows:

Field< ?>[] getFields();
Field< ?>[] getDeclaredFields();

Let us see an example of the above methods:

package org.arpit.java2blog;

import java.lang.reflect.Field;

class TestClass {
    public int a;
    String b;
}

public class ReflectionTest {
    public static void main(String args[]) {
        try {
            Class c = Class.forName("org.arpit.java2blog.TestClass");
            Field ff[] = c.getFields();

            System.out.println("Using getFields() method");
            System.out.println("=======================");
            for (int i = 0; i < ff.length; i++) {
                System.out.println(ff[i]);
            }
            Field f[] = c.getDeclaredFields();
            System.out.println("=======================");
            System.out.println("Using getDeclaredFields() method");
            System.out.println("=======================");
            for (int i = 0; i < f.length; i++) {
                System.out.println(f[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The above code produces the following result on execution.

Using getFields() method
=======================
public int org.arpit.java2blog.TestClass.a
=======================
Using getDeclaredFields() method
=======================
public int org.arpit.java2blog.TestClass.a
java.lang.String org.arpit.java2blog.TestClass.b

Conclusion

Java’s greatest positives is that the design of Java was made such as to encapsulate a diversely dynamic environment – Classes are loaded dynamically, methods are bound dynamically, variables are created dynamically. This led to the idea of manipulating the classes and viewing them dynamically which materialized as the Reflection API of Java. Reflection helps to make Java a dynamic language that further enhances the benefits of the language.

]]>
https://java2blog.com/java-reflection-tutorial/feed/ 0