Table of Contents
In this post, we will see how to get and set fields using reflection in java.
java.lang.reflect.Field
can 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.
1 2 3 4 |
Class cl=Employee.class; Field[] fields = cl.getFields() |
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
.
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 |
package org.arpit.java2blog; public class Employee { public String name; public int age; public Employee(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Employee [name=" + name + ", age=" + age + "]"; } } |
Create main class named PrivateFieldReflectionMain
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 |
package org.arpit.java2blog; import java.lang.reflect.Field; public class GetSetFieldReflectionMain { public static void main(String[] args) { try { Employee e=new Employee("John",30); Field fieldName = Employee.class.getField("name"); // Getting field value String name=(String) fieldName.get(e); System.out.println("Name of Employee:"+name); // Setting field value fieldName.set(e, "Amit"); System.out.println("Employee's updated name: "+e.getName()); } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) { e.printStackTrace(); } } } |
When you run above class, you will get below output:
Output:
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:
1 2 3 4 5 |
public class Employee { public static String name; |
then you can get and set field as below:
1 2 3 4 5 6 7 8 |
// Getting field value String name=(String) fieldName.get(null); System.out.println("Name of Employee:"+name); // Setting field value fieldName.set(null, "Amit"); |
That’s all about how to get and set Fields using reflection in java.