Skip to content

Module access

Brian S. O'Neill edited this page Apr 10, 2022 · 5 revisions

Sometimes it's necessary for a dynamically generated class to have access to packages which aren't exported by the module which is creating it. Such packages might contain implementation-specific features, and requiring that they be exported would be inconvenient. Note that this is an issue only when using the Java module system, which provides stronger access controls. Without modules, implementation packages are effectively public, and are therefore accessible by generated classes.

To enable access to these packages when using the module system, the class which is generating the new class must add module exports beforehand.

// The maker for the class being generated.
ClassMaker cm = ...

// Obtain the module of the class which is generating the new class.
Module thisModule = getClass().getModule();

// Obtain the module of the generated class before it's finished.
Module thatModule = cm.classLoader().getUnnamedModule();

// Export the necessary packages to the module of the generated class.
thisModule.addExports("my.app.impl", thatModule);
thisModule.addExports(..., thatModule);

It's only necessary to add exports for a given ClassLoader instance once, but there's no harm in doing so redundantly. This can prevent problems in case the expected ClassLoader were to change.

Clone this wiki locally