How to access a field's value in an object using reflection

被刻印的时光 ゝ 提交于 2019-12-03 09:20:55
Michael Berry

Before you get a private field, you need to call setAccessible(true); on the corresponding field:

for (Field field : fields) {
    field.setAccessible(true); // Additional line
    System.out.println("Field Name: " + field.getName());
    System.out.println("Field Type: " + field.getType());
    System.out.println("Field Value: " + field.get(person));
}
Marko Topolnik

By default you are not allowed to read non-public fields, but simply invoking field.setAccessible(true); will allow access. In other words, your code should say

for (Field field : fields) {
  field.setAccessible(true);
  // ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!