How to invoke method using reflection in java

In this post, we will see how to invoke the method using reflection in java.
[toc]
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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.