How to access a field's value in an object using reflection
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));
}
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);
// ...
}