Command Palette

Search for a command to run...

Back to the lesson: Topic 15.2 — Reflection
Core Java · Example 3 of 4 Java 9+

The module wall around JDK internals

The real message ends with "to unnamed module @<hash>"; the hash changes every run, so the example cuts it off.

Reflection (java.lang.reflect) lets a running program examine classes it was never compiled against: list their fields, methods and constructors, create objects, call methods and read fields by name. It powers frameworks, serializers and test runners, at the cost of speed, compile-time safety and encapsulation, and since Java 16 the module system blocks it from reaching into JDK internals.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write toMap(Object o) that returns a TreeMap of every declared field name to its value, using reflection, and print it for an object with three private fields.

02

Call a static method Math.max(int, int) through reflection and print the result.

03

Write a method that copies every non-static field from one object to another of the same class, and show it working.

Explain it without notes

01

What is reflection, and where is it used in real systems?

02

What is the difference between getMethods() and getDeclaredMethods()?

03

Why does a reflective call throw InvocationTargetException, and how do you handle it?

04

How did the module system change what setAccessible(true) can do?

05

What are the costs of reflection, and what are the alternatives?

The module wall around JDK internals Java 9+
Sign in to run this example in your browser.

Expected output

found: value of type byte[]
trySetAccessible: false
InaccessibleObjectException: Unable to make field private final byte[] java.lang.String.value accessible: module java.base does not "opens java.lang"
my own class is in a named module: false
String's module: java.base
java.lang open to me: false