How can I use reflection with Java 9 on the internal internal elements of Java?

We use this type of reflection only in our test environment, and not in production. We want to add some jar files to the application class loader depending on our test code. Is there any workaround? How can we access non-exported classes?

java.lang.reflect.InaccessibleObjectException: Unable to make member of class jdk.internal.loader.ClassLoaders$AppClassLoader accessible: module java.base does not export jdk.internal.loader to unnamed module @9f73a2 at jdk.internal.reflect.Reflection.throwInaccessibleObjectException(Reflection.java:414) at java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:174) at java.lang.reflect.Method.checkCanSetAccessible(Method.java:191) at java.lang.reflect.Method.setAccessible(Method.java:185) 
+5
source share
1 answer

Access to the internal classes of the module is not possible from the code. This is special. But there is a temporary solution from the command line - a non-standard option in java that does what you want:

 --add-exports <module>/<package>=<target-module>(,<target-module>)* updates <module> to export <package> to <target-module>, regardless of module declaration. <target-module> can be ALL-UNNAMED to export to all unnamed modules. 

Note

Java 9 is a moving target, and the exact syntax has been changed a couple of times - like this answer. This means that (a) some of the comments below may seem outdated and (b) the flag may not work like that. Please leave a comment and it will be fixed.

+6
source

All Articles