Video in progress

Strong Middle ☕ Core Java

After moving to Java 17, InaccessibleObjectException started appearing. What is it and how do you fix it?

Since Java 16, the JDK's internal packages are strictly closed: setAccessible(true) on a private member of a package that isn't opened no longer works. You upgrade the library, or otherwise temporarily pass --add-opens.

📖 Answer

Modules appeared in Java 9, but in 9-15, reflective access into the JDK only gave a warning ("illegal reflective access"). In Java 16 the default became deny, and in Java 17 the --illegal-access flag was removed altogether.

A typical error:

java.lang.reflect.InaccessibleObjectException:
Unable to make field private final byte[] java.lang.String.value accessible:
module java.base does not "opens java.lang" to unnamed module

The culprit is usually an old library (an old Lombok, Gson, Mockito, Kryo, Groovy) trying to reach private fields of JDK classes.

How I fix it:

  1. Find from the stack trace which library made the call, and upgrade it to a version that supports Java 17. In most cases that's enough.
  2. If that's not possible, temporarily:
java --add-opens java.base/java.lang=ALL-UNNAMED -jar app.jar

Or, in a fat jar's MANIFEST.MF, Add-Opens: java.base/java.lang. 3. If your own code is doing this, stop: JDK internals change with every version.

Note that reflection on private fields in your own classes still works, because code on the classpath lives in the "unnamed module", which opens everything.