Qualified Opens Directive
Sometimes it is necessary that only certain modules can access an open package for reflection. This can be achieved by using the opens-to directive, as shown below at (1), where package org.liberal.sesame in module org.liberal is only open to modules com.aladdin and forty.thieves. This is known as a qualified opens directive. The to clause can be used to specify a comma-separated list of modules that can inspect the open package.
module org.liberal {
opens org.liberal.sesame to com.aladdin, forty.thieves; // (1) Qualified opens
opens org.liberal.pandorasbox; // (2) Unqualified opens
}
Apart from modules com.aladdin and forty.thieves, no other module can inspect package org.liberal.sesame in module org.liberal. Any attempt made by other modules to inspect package org.liberal.sesame will result in a java.lang.Illegal-AccessException. Unqualified open package org.liberal.pandorasbox, shown at (2), allows any module to inspect this package.
The declaration of module controller can be modified to use the qualified opens directive, as shown below. The application adviceOpen can be compiled and run as before.
module controller {
requires model;
requires view;
opens com.passion.controller to main; // Package is only open to main module.
}
Open Modules
An open module can be declared with the restricted keyword open in its declaration file module-info.java:
open module module_name {
// Any number of module directives, except the opens directive.
}
An open module does not declare any open packages, since its declaration implies that all its packages are open. However, note that making a module open also means that it would be possible to use reflection on all types and their members in all packages in the module. Making a module open should be done judiciously, and in a way that does not weaken the principle of encapsulation.
The declaration of module controller can be modified so that the module is open for other modules, as shown below. The application adviceOpen can be compiled and run as before.
open module controller { // An open module
requires model;
requires view;
}
Leave a Reply