Invoke Getters And Setters Using Reflection in java

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.

Create InvokeGetterSetterMain to call getters and setters on employee object.

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.

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

Was this post helpful?

Leave a Reply

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