-1

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?

Michael
  • 13,950
  • 57
  • 145
  • 288

1 Answers1

4

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thank you for the post. In the class, I have @Data annotation, I should create public Set props, any idea how can I use it to access and modify fields value? – Michael Jul 24 '21 at 03:24
  • 1
    @Michael Use `getMethod("setName", String.class)`, then call `method.invoke("Foo")`. Since the method is public, you don't need to use `getDeclaredMethod` and you don't need to call `setAccessible`. – Andreas Jul 24 '21 at 03:28
  • @Andreas, thanks for this great comment. Can you create a post, please? – Michael Jul 24 '21 at 04:26
  • 1
    @Michael - what you have done is asked a >different< question in a comment. Putting an answer to that comment that into an Answer to your original Question wouldn't make much sense. I expect that's why Andreas didn't do that in the first place. – Stephen C Jul 24 '21 at 04:33