[英]Using Java reflection, can I access a private field of type private static nested class?
[英]Why I can't access to field class using reflection?
我在我的項目中使用 java spring。 我嘗試訪問該屬性並使用反射將其設置為特定值。
我嘗試訪問 User 類的 name 屬性:
@Data
public class User {
@Id
private String id;
private String name;
private String phone;
private String email;
}
在這里,我如何嘗試訪問名稱字段:
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;
}
但在這一行:
filed = cls.getField(fieldName);
我收到此錯誤:
java.lang.NoSuchFieldException: name
我的問題是為什么找不到“名稱”字段?
我的問題是為什么找不到“名稱”字段?
getField
方法不返回私有字段。 您需要使用getDeclaredField
來獲取私有字段。 但是getDeclaredField
只返回目標類的字段。
因此,要查找和更新私有字段(在給定類中),您需要執行以下操作:
Field field = User.class.getDeclaredField("name");
field.setAccessible(true);
field.set(userObject, value);
(請注意,您還需要使用setAccessible
來允許訪問私有字段。)
如果要在給定類的某個超類中設置命名私有字段,則需要使用getSuperclass()
遍歷超類鏈,直到找到具有您要查找的字段的Class
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.