相关文章推荐
豪气的双杠  ·  Spring Webflux - aop ...·  2 周前    · 
傲视众生的酱肘子  ·  sqlalchemy session ...·  1 年前    · 
喝醉的跑步机  ·  Java 8 ...·  2 年前    · 

spring reflectionutils set field value example

在 Spring 框架中,可以使用 ReflectionUtils 类的 setField 方法设置对象的字段值。以下是一个示例:

假设我们有一个名为 User 的 Java 类,其中有一个名为 username 的私有字段:

public class User {
    private String username;
    public String getUsername() {
        return username;
    public void setUsername(String username) {
        this.username = username;

现在,我们想要使用 ReflectionUtils.setField 方法设置 User 对象的 username 字段值。以下是示例代码:

import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
public class Main {
    public static void main(String[] args) {
        User user = new User();
        String fieldName = "username";
        String fieldValue = "john_doe";
        // 使用 ReflectionUtils.setField 方法设置字段值
        Field field = ReflectionUtils.findField(User.class, fieldName);
        ReflectionUtils.makeAccessible(field);
        ReflectionUtils.setField(field, user, fieldValue);
        System.out.println(user.getUsername()); // 输出 "john_doe"

在上述代码中,我们首先创建了一个 User 对象,然后指定要设置的字段名称和字段值。接下来,我们使用 ReflectionUtils.findField 方法找到 User 类中的 username 字段,使用 ReflectionUtils.makeAccessible 方法打开私有字段的访问权限,最后使用 ReflectionUtils.setField 方法设置字段值。最后,我们使用 user.getUsername() 方法检查 username 字段是否已成功设置。

需要注意的是,ReflectionUtils 类需要添加 spring-core 依赖才能使用。

  •