Home> Java> javaTutorial> body text

How does Java reflection mechanism set field values?

PHPz
Release: 2024-04-15 22:18:01
Original
1133 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 theField.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 aPersonclass that has a private fieldage. We can set the value ofageusing 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 usesetAccessible(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 theField.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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!