Search code examples
javadebuggingencapsulationaccess-modifiers

Java: How does the debugger show private fields?


If fields defined in a Java class as 'private' are only accessible from within their own class - how does the debugging tool show them and their values when we are walking through an executing code?

Picture-In-Picture Screenshot for illustration: enter image description here

My best guess is that the JVM has a debugging mode that allows a special debugging package to access these. Running in debugging mode (such as a debug configuration from the IDE) allows this special package (which the IDE knows to use) to do its thing.

It's just interesting... No work is reliant on your answer here :)


Solution

  • In a JVM based on the OpenJDK codebase, a debugger uses a JVMTI agent to access the state of the program being debugged. The agent makes calls to the JVMTI native API. This allows agent (and hence the debugger) to read and write the values of object fields, local variables and so on. The JVMTI APIs ignore accessibility. (In the same way that the JNI APIs do.)

    For more information, read the JVM Tools Interface documentation.

    For a broader view, see the Java Platform Debugger Architecture documentation. JVMTI is part of that architecture.