Quick revision
The short answer
We walk from obj.getClass() up through getSuperclass() until we reach Object, and for each class we call getDeclaredFields(), skip static and synthetic fields, make each field accessible and print field.get(obj). We must handle IllegalAccessException and, on modern JDKs, InaccessibleObjectException for classes in modules that do not open their packages, plus null input and arrays. That last exception is why the code fails for a java.util.ArrayList.
What to remember
In this answer, we wrote a field dumper that walks from obj.getClass() up through getSuperclass(), lists each class's own fields with getDeclaredFields(), skips static and synthetic fields such as this$0, makes each field accessible and prints its value. We handled null, arrays, IllegalAccessException and the InaccessibleObjectException that strong encapsulation raises for JDK classes such as ArrayList, and we saw that the fix there is the public API rather than forcing the package open.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We walk from obj.getClass() up through getSuperclass() until we reach Object, and for each class we call getDeclaredFields(), skip static and synthetic fields, make each field accessible and print field.get(obj). We must handle IllegalAccessException and, on modern JDKs, InaccessibleObjectException for classes in modules that do not open their packages, plus null input and arrays. That last exception is why the code fails for a java.util.ArrayList.
Why this question is asked
Dumping an object's state is a classic reflection exercise, and the same loop sits inside real tools: debug loggers, test assertion libraries that compare objects field by field, and serialisers. Interviewers use it because a working answer needs several details that are easy to forget: inherited private fields, static fields, compiler-generated fields and the module system. In this answer, we will recap why one call is not enough, write the method step by step, run it on an example, look at the edge cases, and explain the ArrayList failure.
1Why getDeclaredFields() Alone Is Not Enough
Reflection offers two ways to list fields. getFields() returns only public fields, including inherited ones, which misses almost everything, because well-written classes keep fields private. getDeclaredFields() returns every field declared in one class, private ones included, but nothing inherited from its superclasses.
An Employee object, though, also contains the private fields declared in Person, its superclass. They are part of the object's state; Employee's code just cannot see them by name. So to print the whole state we must call getDeclaredFields() on each class in the hierarchy: Employee, then Person, and so on, until we reach Object, which declares no instance fields worth printing.
- Start at obj.getClass()for example Employee
- Call getDeclaredFields()private, protected and public fields of this class only
- Static or synthetic?YesSkip itNoMake it accessible and print it
- Move to getSuperclass()Employee -> Person -> Object
- Reached Object or null?YesStopNoRepeat for this class
5 steps in order. Play them, or step through them one at a time.
2Writing the Field Dumper
Here is the method. Each line handles one of the rules above.
Notice the loop condition. We stop when getSuperclass() returns null, which happens for Object itself and for interfaces and primitives, and we also stop at Object because it has no instance fields. The reason for skipping static fields is that they belong to the class, not to this object; if we want them, we can print them once per class. trySetAccessible() is the modern form of setAccessible(true): instead of throwing InaccessibleObjectException, a RuntimeException, it returns false, which keeps the loop simple. If we use setAccessible(true), we must catch InaccessibleObjectException ourselves.
3Running It on an Example
Let us try it on a small hierarchy with private fields in both classes, a static field and an inner class.
So the subclass fields come first and the superclass fields follow, and COUNT does not appear because it is static. Within a class, the order of getDeclaredFields() is not guaranteed by the specification, even though it usually follows the source; if the output must be stable, sort the fields by name.
4Edge Cases to Handle
Inner classes are the first surprise. A non-static inner class like Badge needs a reference to its outer Employee, and the compiler adds a hidden field for it, traditionally named this$0. It is marked synthetic, meaning generated by the compiler and not present in the source, so isSynthetic() lets us filter it. Recent javac versions may leave the field out when the inner class never uses its outer instance, so do not rely on it being there either.
Field values bring the second set of issues. f.get(obj) boxes primitives, so an int prints as an Integer. A field that refers to another object prints that object's toString(), which may itself be huge or fail; if we wanted to dump recursively, we would need a set of visited objects to avoid looping forever on cycles such as a parent pointing to a child that points back. Records work fine, since their components are ordinary private final fields, and for a record we could also use getRecordComponents(), which gives the accessors in declaration order.
Finally, the module system. Our own classes on the class path are in the unnamed module, and deep reflection inside it is always allowed. Classes from the JDK or from named modules allow it only if their package is opened to us, which is the case behind the follow-up question.
5Why It Fails for a java.util.ArrayList
An ArrayList keeps its elements in a private field called elementData, and its superclass AbstractList has a protected field modCount. Both live in the java.util package of the java.base module. Since JDK 16, strong encapsulation is the default, and since JDK 17 there is no option to relax it globally, so java.base does not open java.util to our code.
The right response is usually not to force the field open. For JDK types we should use their public API, size() and iteration for a list. If a test tool truly needs the internals, the JVM option --add-opens java.base/java.util=ALL-UNNAMED opens the package, but that is a workaround to document, not a default.
6Follow-up questions
Why might this fail for a java.util.ArrayList instance in recent JDKs?
Because ArrayList's fields are private members of a class in java.base, and java.base does not open java.util to the unnamed module where our code runs. Since JDK 16 strong encapsulation is the default and JDK 17 removed the --illegal-access switch, so setAccessible(true) throws InaccessibleObjectException, and trySetAccessible() returns false. The fix is to use the public API, or as a documented workaround --add-opens java.base/java.util=ALL-UNNAMED.
Should we skip transient fields too?
It depends on the purpose. transient marks fields that are not part of the serialised state, such as caches, so a serialiser or an equality checker usually skips them with Modifier.isTransient. A debug dump may want to see them. ArrayList's elementData is transient, which shows that the keyword describes serialisation, not importance.
Is there a faster way to read the same fields repeatedly?
Yes. For repeated access we can find the fields once, cache them per class, and either keep the Field objects or convert them to MethodHandles or VarHandles with MethodHandles.privateLookupIn, which perform better on hot paths. Searching the hierarchy on every call is the slow part.
7Conclusion
In this answer, we wrote a field dumper that walks from obj.getClass() up through getSuperclass(), lists each class's own fields with getDeclaredFields(), skips static and synthetic fields such as this$0, makes each field accessible and prints its value. We handled null, arrays, IllegalAccessException and the InaccessibleObjectException that strong encapsulation raises for JDK classes such as ArrayList, and we saw that the fix there is the public API rather than forcing the package open.
Open with
I'd start with obj.getClass() and loop up the hierarchy with getSuperclass(), stopping at Object or null, because getDeclaredFields() only returns the fields declared in one class, while getFields() only returns public ones.
Then, if they want more
For each class I call getDeclaredFields() and skip static fields with Modifier.isStatic, since they belong to the class, and synthetic fields with isSynthetic, like the this$0 reference the compiler adds to inner classes. For each remaining field I call trySetAccessible, or setAccessible(true), and then field.get(obj), printing the class name, field name and value.
For exceptions: field.get throws the checked IllegalAccessException, and setAccessible throws InaccessibleObjectException, a runtime exception, if the class is in a module that doesn't open that package to me. trySetAccessible returns false instead, which keeps the loop clean.
Other edge cases: a null object, arrays, which have no declared fields so I'd use java.lang.reflect.Array, primitives being boxed, the unspecified order of fields, and cycles if I made it recursive, which needs a visited set.
ArrayList is the classic failure: its elementData field is private in java.base, and since JDK 16 and 17 java.util isn't opened to the unnamed module, so I'd use its public API instead of forcing --add-opens.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 16, Java 17
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write code that, given any object, prints the names and values of all its fields...": https://scrivio-interview-library.netlify.app/java/reflection-and-method-handles/781bf2d585/