简体   繁体   中英

Why I can't access to field class using reflection?

I use java spring for my project. I try to access the property and set it with a specific value using the reflection.

I try to access the name property of User class:

@Data
public class User {
    @Id
    private String id;
    private String name;
    private String phone;
    private String email;
}

Here how I try to access the name field:

User newUser = userRepository.get(id); 
User user = accessProp(newUser, User.class, "name", "John");


public <D> D accessProp(Class<D> dest, String fieldName, Object value ){
    Field filed = null;
    var cls = AdminUser.class;

    filed = cls.getField(fieldName);
    filed.set(dest, value);

    return dest;
}

But on this row:

 filed = cls.getField(fieldName);
 

I get this error:

 java.lang.NoSuchFieldException: name
 

My question is why "name" field not found?

My question is why is the "name" field not found?

The getField method does not return private fields. You need to use getDeclaredField to get a private field. But getDeclaredField only returns fields for the target class.

So to find and update a private field (in the given class) you need to do something like this:

Field field = User.class.getDeclaredField("name");
field.setAccessible(true);
field.set(userObject, value);

(Notice that you also need to use setAccessible to allow access to a private field.)

If you wanted to set a named private field in some superclass of a given class, you would need to use getSuperclass() to traverse the superclass chain until you found the Class that has the field you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM