Home > Java > javaTutorial > How does Java reflection mechanism set field values?

How does Java reflection mechanism set field values?

PHPz
Release: 2024-04-15 22:18:01
Original
1228 people have browsed it

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.

How does Java reflection mechanism set field values?

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 the Field.set() method. This method accepts two parameters:

  • Target object
  • New value to be set

Syntax:

field.set(目标对象, 新值);
Copy after login

Code Example:

Suppose we have a Person class that has a private field age. We can set the value of age 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;
    }
}
Copy after login

Note:

  • To access private fields we need to use setAccessible(true) Method removes the privacy of a field.
  • You can also set protected or package access fields.
  • If you do not want to modify the original object, you can also use the 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template