How to invoke method using reflection in java

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.

Create a main method named EmployeeReflectionMain.java.

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.

Invoke method without parameters

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

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

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

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

Was this post helpful?

Leave a Reply

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