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));
}

Leave a Comment