Applying --add-opens Option to Dynamically Loaded Modules in Java 17

2.4k Views Asked by At

In the context of JEP 403's robust encapsulation in Java 17, I have a class (.jar) that is dynamically loaded during JVM execution.
This class utilizes Reflection to invoke private methods belonging to the ClassLoader.

The JVM addresses this with the CLI option --add-opens, which allows specifying modules so that Reflection works successfully.
However, it seems that this approach is not applicable to modules that are loaded dynamically, meaning modules loaded after startup.

Currently, I am using like --add-opens java.base/java.lang=foobar and below code.

try
{
    Method method = ClassLoader.class.getDeclaredMethod("findLoadedClass", String.class);
    method.setAccessible(true);
    // ...
}
catch (NoSuchMethodException | InaccessibleObjectException e)
{
    // InaccessibleObjectException will be thrown.
}

Then I got this warning on startup: WARNING: Unknown module: foobar specified to --add-opens

In an attempt to work around this limitation, I removed the module-info.class from my .jar, intending to load it as an unnamed module and use --add-opens for ALL_UNNAMED modules at JVM startup. However, this approach is not viable due to other technical constraints.

Could someone please guide me on how to use --add-opens effectively for modules that are loaded dynamically after JVM startup?
Is there an alternative approach I should consider?

Thank you in advance for your assistance.

1

There are 1 best solutions below

0
mohsen_true On

suppose you are faced with this error: module java.base does not "opens java.security" to unnamed module @75226b29

so to solve this, you must get "java.base" to open "java.security" to module unnamed module @75226b29 and as every time this module's name changes, you must open it for all unnamed modules with the below command:

--add-opens java.base/java.security=ALL-UNNAMED