Video in progress
A library that worked on Java 8 throws InaccessibleObjectException on Java 17. Why, and what does --add-opens do?
Since Java 16-17 the JDK's internal packages are strongly encapsulated: reaching private members through reflection with setAccessible(true) is now forbidden by default. --add-opens opens one specific package of one specific module for reflection.
📖 Answer
Java 9 introduced the module system, but for a long time it ran in a "soft" mode: if you reached into internal APIs through reflection, you only got a warning. JDK 16 changed the default to deny, and JDK 17 (JEP 403) removed the --illegal-access flag as well.
As a result, an old library fails like this:
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 @1b6d3586
The temporary fix:
java --add-opens java.base/java.lang=ALL-UNNAMED -jar app.jar
The format is module/package=target. Ordinary code on the classpath counts as ALL-UNNAMED.
But this is a patch. The real fix is to upgrade the library, because modern versions (Lombok, Mockito, Kryo, older Spring/Hibernate) have already solved this. jdeps --jdk-internals app.jar shows which library uses internal APIs.
sun.misc.Unsafe is the exception: it lives in the jdk.unsupported module and is still open, but its memory methods are also on their way out.
Sign up to mark studied questions and save your progress.