Explain Codes LogoExplain Codes Logo

How to solve InaccessibleObjectException ("Unable to make {member} accessible: module {A} does not 'opens {package}' to {B} ") on Java 9?

java
reflective-access
module-access
java-9
Alex KataevbyAlex Kataev·Nov 26, 2024
TLDR

Resolve the InaccessibleObjectException by using the JVM's --add-opens flag:

// Lifehack: Coffee isn't the only java that helps you solve problems! java --add-opens {A}/{package}={B} -jar app.jar

Replace {A} with the limiting module, {package} with the desired package, and {B} with either your module or ALL-UNNAMED. Incorporate this flag into your IDE's run/debug configurations for an immediate effect. Just remember: while this is an effective band-aid, you should strive towards proper module access management for a sustainable solution.

Securing good neighbors: Long-term module interaction in Java 9

Java 9 saw the emergence of libraries like Spring, Hibernate, and JAXB facing InaccessibleObjectException. Thankfully, library maintainers are diligently working to lift module access restrictions. Thus, always verify for library updates tailored for Java 9 and beyond. Use community resources like official documentation or repository announcements for relevant updates.

The paradox of JDK 17: Strict encapsulation vs. unrestricted module access

As the saying goes, "What happens in a module remains in a module" – especially from JDK 17 onwards! Understanding JEP 403 is paramount as it influences the module system and class accessibilities. Notably, the jdk.unsupported module offers continuity for sun.misc and sun.reflect use.

Bye, --permit-illegal-access, Hi, specific flags!

From JDK 17 onwards, the handy-dandy --permit-illegal-access has been deprecated. This once-playful puppy that gave unrestricted reflective access has grown up. Therefore, a more behaved and specific approach is necessary using --add-opens or tweaking the module manifest Add-Opens directives to stay within the rules.

Digging into JDK internals

For reflective calls, the JVM --add-opens option is like your fairy godparent. It informs the JVM which package of a module to make accessible and for which module. But remember, just like Cinderella at a ball, this joyride is temporary. For longevity and maintainability, modifying the module-info.java or seeking reflection alternatives is advisable.

Eclipse settings and IDE harmony

Working in Eclipse? Double-check your compiler level and JRE installation path to match the Java version targeted by your project. Java doesn't play favorites; running different JDK versions between development and runtime may trigger the InaccessibleObjectException monster. So, keep things consistent! When running your application from the terminal, directly pass the --add-opens flag to the JVM.