How to resolve “java.lang.IllegalAccessError” OR “unnamed module cannot access class” Error in java 17
After Java 17 upgrade some of you might have face this “java.lang.IllegalAccessError” or “unnamed module cannot access class” error and you might have try to use --illegal-access=permit
or --illegal-access=warn
but after Java 16 release, it will no longer be possible for end users to use the --illegal-access
option to enable access to internal elements of the JDK. let’s see how to solve this error.
— — — — — — — —
First approach:
Understand how the Java Platform Module System works. In JPMS, classes belong to modules, and access to classes from other modules is controlled by module descriptors (module-info.java
). then ensure that your module declarations (module-info.java
) are correctly specifying the necessary exports
and opens
directives to allow other modules to access the required packages and classes.
If you’re using third-party libraries or frameworks, ensure that their modules are accessible to your module. You may need to add dependencies in your module-info.java
file using requires
.
— — — — — — — —
If you are in hurry second approach might be for you,
Second approach:
Easiest way to use --add-exports
and --add-opens
Flags in Java options.
The --add-exports
option enables access to the public types of a specified package.
syntax: --add-exports=<source-module>/<package>=<target-module>
It is sometimes necessary to go further and enable access to all non-public elements. This is were the --add-opens
option can be used, at run time, to do this. It has the same syntax as the --add-exports
option:
syntax: --add-opens=<source-module>/<package>=<target-module>
where <source-module>
and <target-module>
are module names and <package>
is the name of a package.
Example: if the <target-module>
is ALL-UNNAMED
then the source package will be exported to all unnamed modules, whether they exist initially or are created later on. Thus access to the sun.management
package of the java.management
module can be granted to all code on the class path via the option --add-exports=java.management/sun.management=ALL-UNNAMED
finally it will looks like this,
java --add-exports=java.management/sun.management=ALL-UNNAMED
if you wants your java code to take this option from environment variable and append it to existing options. you can use
export JAVA_OPTS= --add-exports=java.management/sun.management=ALL-UNNAMED
The --add-exports
and --add-opens
options must be used with great care. You can use them to gain access to an internal API of a library module, or even of the JDK itself, but you do so at your own risk: If that internal API is changed or removed then your library or application will fail.
Thank you for taking the time to read my blog. If you found the content helpful or interesting, please consider giving it a clap! 👏 Your support is greatly appreciated.