Get and set Fields using reflection in java


In this post, we will see how to get and set fields using reflection in java.

java.lang.reflect.Fieldcan be used to get/set fields(member variables) at runtime using reflection.

Get all fields of the class

All fields of the class can be obtained from the Class object. Here is an example.

Field[] will have all the public fields of the class.

Get particular field of the class

If you already know name of the fields you want to access, you can use cl.getField(String fieldName) to get Field object.

Getting and setting Field value

Field.get() and Field.set()methods can be used get and set value of field respectively.
Let’s understand with the help of example.
Consider a class named Employee which consists of two private fields name and age.

Create main class named PrivateFieldReflectionMain

When you run above class, you will get below output:

Name of Employee:John
Employee’s updated name:Amit

Please note that Here parameter to get() and set() should be object of the class to which field belongs.
For example:
In this case, name field belongs to Employee class, we have passed e to get() and set() method of field object.

Getting and setting static Field value

In case, you want to get and set static field, then you need to pass null while using get() and set() method of Field.
For example:

then you can get and set field as below:

That’s all about how to get and set Fields using reflection in java.


Add Comment