In this post, we will see how to invoke the method using reflection in java.
Table of Contents
Create a class named
Employee.java
. We will invoke this class’s method using reflection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
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
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
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<Employee> 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<Employee>) 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.
1 2 3 |
Class cls = (Class) Class.forName("org.arpit.java2blog.methodinvocation.Employee"); |
Invoke method without parameters
1 2 3 4 5 6 7 8 |
//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
1 2 3 4 5 6 7 8 9 |
//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
1 2 3 4 5 6 |
//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
1 2 3 4 5 6 7 8 9 |
//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.