Invoke Getters And Setters Using Reflection in java

Previous
Next

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

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog