×
☰ See All Chapters

Java module open, opens, and opens…to directives

opens and opens… to directives are used to allow package to user modules or to selected modules. open directive is used to allow all packages of a module to all user modules. Before Java 9, reflection can access all members of any type even its private members. Data types failed to encapsulate its members when its private members are accessible using reflection.

java-module-opens-0
 

The above feasibility of accessing the private members via reflection is not possible unless the creator of the library could add opens packagename; (opens com.java4coding.demo;) to the module descriptor.  If opens directive does not declare the package then java.lang.reflect.InaccessibleObjectException will be thrown at runtime.

java-module-opens-1
 

Allowing packages to all modules

Below syntax will allow package to all user modules. Any module can access the package com.java4coding.demo in reflection.

opens packagename;

Example:

module com.java4coding.demo {

        exports com.java4coding.demo;

        opens com.java4coding.demo;

}

Allowing packages to selected modules

Below syntax will allow package to selected modules.

opens packagename to modulename;

Example:

module com.java4coding.demo {

        exports com.java4coding.demo;

        opens com.java4coding.demo to com.java4coding.test;

}

 

Only com.java4coding.test module can access the package com.java4coding.demo in reflection.

Allowing all packages to all modules

Below syntax will allow all packages of a module to all user modules.

open module modulename {

        // module directives

}

Example:

open module com.java4coding.demo {

        exports com.java4coding.demo;

}

All packages of module com.java4coding.demo will be accessible by all user modules.


All Chapters
Author