7
java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.lang.Object java.util.Optional.value accessible: module java.base does not "opens java.util" to unnamed module @6b26e945

I am getting this error when I run my JUnit code. Error arises around the following code block.

Optional<RolesDTO> roleDTOEmployee = roles.stream()
        .filter(r -> r.getName().equals(RolesEnum.valueOf(roleName).getRoleName())).findFirst();

if (logger.isInfoEnabled()) {
    logger.info("roleDTOEmployee {}", gson.toJson(roleDTOEmployee));
}

stacktrace:

at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
    at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:178)
    at java.base/java.lang.reflect.Field.setAccessible(Field.java:172)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:157)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
    at com.google.gson.Gson.getAdapter(Gson.java:423)
    at com.google.gson.Gson.toJson(Gson.java:661)
    at com.google.gson.Gson.toJson(Gson.java:648)
    at com.google.gson.Gson.toJson(Gson.java:603)
    at com.google.gson.Gson.toJson(Gson.java:583)

on removing logger.info(), code JUnit runs perfectly. I would like to understand this behaviour. And is there a workaround it, so I don't have to remove logger.

1
  • 1
    Does gson.toJson(roleDTOEmployee.orElse(null)) work? It seems like gson doesn't support Optional. Commented Jun 29, 2022 at 17:36

1 Answer 1

6

This error typically thrown if you are using higher JDK version (8+) & one of modules (in this case com.google.gson.Gson is compatible with lower JDK version).

Can you please check both JDK version Gson version downgrade your JDK if possible & required. That way your error might be gone. Other possibility is to upgrade com.google.gson.Gson version so that it is compatible with your JDK.

Another workaround (which is typically not recommended) is pass VM args to avoid above error:

-Xmx1536M --add-exports=java.base/sun.nio.ch=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-exports=jdk.unsupported/sun.misc=ALL-UNNAMED
Sign up to request clarification or add additional context in comments.

1 Comment

yes. version was not compatible. on upgrading it works too. thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.