简体   繁体   中英

java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.lang.Object java.util.Optional.value accessible:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM