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

157,509

Solution 1

The exception is caused by the Java Platform Module System that was introduced in Java 9, particularly its implementation of strong encapsulation. It only allows access under certain conditions, the most prominent ones are:

  • the type has to be public
  • the owning package has to be exported

The same limitations are true for reflection, which the code causing the exception tried to use. More precisely the exception is caused by a call to setAccessible. This can be seen in the stack trace above, where the corresponding lines in javassist.util.proxy.SecurityActions look as follows:

static void setAccessible(final AccessibleObject ao,
                          final boolean accessible) {
    if (System.getSecurityManager() == null)
        ao.setAccessible(accessible); // <~ Dragons
    else {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                ao.setAccessible(accessible);  // <~ moar Dragons
                return null;
            }
        });
    }
}

To make sure the program runs successfully the module system must be convinced to allow access to the element on which setAccessible was called. All information required for that is contained in the exception message but there are a number of mechanisms to achieve this. Which is the best one depends on the exact scenario that caused it.

Unable to make {member} accessible: module {A} does not 'opens {package}' to {B}

By far the most prominent scenarios are the following two:

  1. A library or framework uses reflection to call into a JDK module. In this scenario:

    • {A} is a Java module (prefixed with java. or jdk.)
    • {member} and {package} are parts of the Java API
    • {B} is a library, framework, or application module; often unnamed module @...
  2. A reflection-based library/framework like Spring, Hibernate, JAXB, ... reflects over application code to access beans, entities,... In this scenario:

    • {A} is an application module
    • {member} and {package} are part of the application code
    • {B} is either a framework module or unnamed module @...

Note that some libraries (JAXB, for example) can fail on both accounts so have a close look at what scenario you're in! The one in the question is case 1.

1. Reflective Call Into JDK

The JDK modules are immutable for application developers so we can not change their properties. This leaves only one possible solution: command line flags. With them it is possible to open specific packages up for reflection.

So in a case like above (shortened)...

Unable to make java.lang.ClassLoader.defineClass accessible: module java.base does not "opens java.lang" to unnamed module @1941a8ff

... the correct fix is to launch the JVM as follows:

# --add-opens has the following syntax: {A}/{package}={B}
java --add-opens java.base/java.lang=ALL-UNNAMED

If the reflecting code is in a named module, ALL-UNNAMED can be replaced by its name.

Note that it can sometimes be hard to find a way to apply this flag to the JVM that will actually execute the reflecting code. This can be particularly tough if the code in question is part of the project's build process and is executed in a JVM that the build tool spawned.

If there are too many flags to be added, you might consider using the encapsulation kill switch --permit-illegal-access instead. It will allow all code on the class path to reflect overall named modules. Note that this flag will only work in Java 9!

2. Reflection Over Application Code

In this scenario, it is likely that you can edit the module that reflection is used to break into. (If not, you're effectively in case 1.) That means that command-line flags are not necessary and instead module {A}'s descriptor can be used to open up its internals. There are a variety of choices:

  • export the package with exports {package}, which makes it available at compile and run time to all code
  • export the package to the accessing module with exports {package} to {B}, which makes it available at compile and run time but only to {B}
  • open the package with opens {package}, which makes it available at run time (with or without reflection) to all code
  • open the package to the accessing module with opens {package} to {B}, which makes it available at run time (with or without reflection) but only to {B}
  • open the entire module with open module {A} { ... }, which makes all its packages available at run time (with or without reflection) to all code

See this post for a more detailed discussion and comparison of these approaches.

Solution 2

It is still possible to try with older JKD version.

For Eclipse you need to do 2 things. Go to

  1. Window -> Preference -> java -> Compiler Set Compiler Compliance Level to Specific version In my case, Eclipse version was set to JDK 16 I reverted it to 1.8 as my code was written in 1.8

  2. Window -> Preferences -> Java -> Installed JREs. Add the JRE installation path (Select Standard VM)

It worked smoothly for me..

Solution 3

Just a recent feedback

Many proposals to solve this issue have to do with the vm launcher option --illegal-access.

According to Oracle, with JEP 403 (link1) and JEP 403 (link2) which has been decided to be delivered from JDK 17 and onwards , the launcher option --illegal-access will stop working!

Summary Strongly encapsulate all internal elements of the JDK, except for critical internal APIs such as sun.misc.Unsafe. It will no longer be possible to relax the strong encapsulation of internal elements via a single command-line option, as was possible in JDK 9 through JDK 16.

And

With this change, it will no longer be possible for end users to use the --illegal-access option to enable access to internal elements of the JDK. (A list of the packages affected is available here.) The sun.misc and sun.reflect packages will still be exported by the jdk.unsupported module, and will still be open so that code can access their non-public elements via reflection. No other JDK packages will be open in this way.

It will still be possible to use the --add-opens command-line option, or the Add-Opens JAR-file manifest attribute, to open specific packages.

So the following solution will keep working

# --add-opens has the following syntax: {A}/{package}={B}
java --add-opens java.base/java.lang=ALL-UNNAMED

But the solution with --illegal-access will stop working from JDK 17 and onwards.

Solution 4

Add --illegal-access=warn and --add-opens java.base/java.lang=ALL-UNNAMED to your eclipse.ini

Solution 5

This is a very challenging problem to solve; and as noted by others, the --add-opens option is only a workaround. The urgency to resolve the underlying issues will only grow once Java 9 becomes publicly available.

I found myself on this page after receiving this exact Javassist error while testing my Hibernate-based application on Java 9. And since I aim to support Java 7, 8, and 9 on multiple platforms, I struggled to find the best solution. (Note that Java 7 and 8 JVMs will abort immediately when they see an unrecognized "--add-opens" argument on the command line; so this can't be solved with static changes to batch files, scripts, or shortcuts.)

It would be nice to receive official guidance from the authors of mainstream libraries (such as Spring and Hibernate), but with 100 days to go until the currently projected release of Java 9, that advice still seems hard to find.

After much experimentation and testing, I was relieved to find a solution for Hibernate:

  1. Use Hibernate 5.0.0 or higher (earlier versions won't work), and
  2. Request build-time bytecode enhancement (using the Gradle, Maven, or Ant plugins).

This avoids the need for Hibernate to perform Javassist-based class modifications at runtime, eliminating the stack trace shown in the original post.

HOWEVER, you should thoroughly test your application afterward. The bytecode changes applied by Hibernate at build-time appear to differ from the ones applied at runtime, causing slightly different application behavior. Unit tests in my app that have succeeded for years suddenly failed when I enabled build-time bytecode enhancement. (I had to chase down new LazyInitializationExceptions and other problems.) And the behavior seems to vary from one version of Hibernate to another. Proceed with caution.

Share:
157,509
Nicolai Parlog
Author by

Nicolai Parlog

Nicolai (aka nipafx) is a Java enthusiast focused on language features and core APIs with a passion for learning and sharing. He does that in blog posts, articles, newsletters, and books; in tweets, repos, videos, and streams; at conferences and in-house trainings - more on all of that on nipafx.dev. That aside, he's best known for his haircut.

Updated on April 26, 2022

Comments

  • Nicolai Parlog
    Nicolai Parlog about 2 years

    This exception occurs in a wide variety of scenarios when running an application on Java 9. Certain libraries and frameworks (Spring, Hibernate, JAXB) are particularly prone to it. Here's an example from Javassist:

    java.lang.reflect.InaccessibleObjectException: Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @1941a8ff
        at java.base/jdk.internal.reflect.Reflection.throwInaccessibleObjectException(Reflection.java:427)
        at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:201)
        at java.base/java.lang.reflect.Method.checkCanSetAccessible(Method.java:192)
        at java.base/java.lang.reflect.Method.setAccessible(Method.java:186)
        at javassist.util.proxy.SecurityActions.setAccessible(SecurityActions.java:102)
        at javassist.util.proxy.FactoryHelper.toClass2(FactoryHelper.java:180)
        at javassist.util.proxy.FactoryHelper.toClass(FactoryHelper.java:163)
        at javassist.util.proxy.ProxyFactory.createClass3(ProxyFactory.java:501)
        at javassist.util.proxy.ProxyFactory.createClass2(ProxyFactory.java:486)
        at javassist.util.proxy.ProxyFactory.createClass1(ProxyFactory.java:422)
        at javassist.util.proxy.ProxyFactory.createClass(ProxyFactory.java:394)
    

    The message says:

    Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @1941a8ff

    What can be done to avoid the exception and have the program run successfully?

  • zhuguowei
    zhuguowei over 7 years
    Is Lombok in case 1 and hard to find a way to apply this flag to the JVM that will actually execute the reflecting code because it is part of the project's build process?
  • Nicolai Parlog
    Nicolai Parlog over 7 years
    Yes, Lombok is case 1. The question how hard it is to apply the flags belongs here.
  • Karussell
    Karussell over 7 years
    Thanks for the explanation. For my very similar case it still fails even with that --add-opens option. Strange.
  • Nicolai Parlog
    Nicolai Parlog over 7 years
    At first glance, the problem might be that you configure the Surefire plugin but the failure is produced by the failsafe-plugin. If I am wrong, please ask a separate question.
  • ZhekaKozlov
    ZhekaKozlov almost 7 years
    @Nicolai I think you should update your answer because JDK 9 now allows illegal access by default and --permit-illegal-access will change to --illegal-access: mail.openjdk.java.net/pipermail/jigsaw-dev/2017-May/012673.h‌​tml
  • Nicolai Parlog
    Nicolai Parlog almost 7 years
    @ZhekaKozlov I'm waiting for the first EA build that exposes that behavior before updating the answer.
  • Gunnar
    Gunnar almost 7 years
    It'd be helpful to know how you suggest to "fix their issues". Is it by means of method or var handles? IMHO accessing state by reading/writing private fields isn't inherently bad, e.g. it's something explicitely foreseen by the JPA spec.
  • Alan Bateman
    Alan Bateman almost 7 years
    For the specific example, it looks like Hibernate or Spring using Javassist to hack into a non-public defineClass method. The Lookup.defineClass method was specifically added to help libraries inject classes so that it is the way forward for that use-case. For the case where JPA and other libraries that need to access private members of their consumers then they will need to document that the consumer opens the package to the library (for annotation based frameworks (like JPA) then that is potentially checkable at build time).
  • bartolo-otrit
    bartolo-otrit over 6 years
    export JAVA_TOOL_OPTIONS="$JAVA_TOOL_OPTIONS --add-opens=java.base/java.lang=ALL-UNNAMED" worked for OpenJDK 9 because of bugs.openjdk.java.net/browse/JDK-8173128
  • Pavel_K
    Pavel_K about 4 years
    Could you take a look at this question stackoverflow.com/questions/60918134/…
  • Krishna Acharya
    Krishna Acharya almost 3 years
    @Nicolai Parlog Can you please tell what canges to make in the modul-info.java file my error is like so: java.lang.reflect.InaccessibleObjectException: Unable to make boolean java.lang.reflect.AccessibleObject.setAccessible0(boolean) accessible: module java.base does not "opens java.lang.reflect" to module com.jfoenix ; with Context to the 2nd solution
  • Johannes Kuhn
    Johannes Kuhn over 2 years
  • Karan Kamboj
    Karan Kamboj over 2 years
    this will work in java 8
  • Johannes Kuhn
    Johannes Kuhn over 2 years
    With java 8: java --illegal-access=warn --add-opens java.base/java.lang=ALL-UNNAMED Foo -> Unrecognized option: --illegal-access=warn, Error: Could not create the Java Virtual Machine., Error: A fatal exception has occurred. Program will exit..
  • Stephen
    Stephen about 2 years
    Also works for IntelliJ, you need to set up the correct project SDK in File -> Project Structure window