Use reflection mechanism to set field value: get field reference through Field.getDeclaredField(). Call the Field.set() method to set the target object's new value.
Java reflection mechanism: setting field values
The reflection mechanism is a way to check and modify classes, methods, and fields at runtime Mechanisms. It allows us to access, set or call private or protected members of a Java program.
Set field value
To set the field value, we can use theField.set()
method. This method accepts two parameters:
Syntax:
field.set(目标对象, 新值);
Code Example:
Suppose we have aPerson
class that has a private fieldage
. We can set the value ofage
using the following code:
import java.lang.reflect.Field; public class Main { public static void main(String[] args) throws Exception { // 实例化 Person 对象 Person person = new Person(); // 获取 Person 类的私有字段 age Field field = person.getClass().getDeclaredField("age"); // 将 age 的值设置为 30 field.set(person, 30); // 输出 age 的值 System.out.println(person.getAge()); // 输出:30 } } class Person { private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Note:
setAccessible(true)
Method removes the privacy of a field.Field.set()
method to create a copy of the field value.The above is the detailed content of How does Java reflection mechanism set field values?. For more information, please follow other related articles on the PHP Chinese website!