×
☰ See All Chapters

How to export packages from Java 9 module - Java module exports

When packages need to be accessible to code in other modules, we have to export those packages using export directive.  When package is exported, the module which uses the exported package can access only public types of that package. When package is made accessible by exporting then all its sub packages will also be accessible.

Syntax

exports package;

 

Example to export packages from Java 9 module

module com.java4coding.app {

exports com.java4coding.util;

}

 

We can export package to any particular module and only specified module can access that package. Below is the syntax to export module to selected modules.

exports package to modulename;

Example to export package to selected module

module com.java4coding.app {

exports com.java4coding.util;

exports  com.java4coding.security to com.java4coding.client;

}

In the above example we have exported com.java4coding.security package from com.java4coding.app module to com.java4coding.client module. This package com.java4coding.security is not exported to com.java4coding.other module; hence we are getting error when we try to access Security class inside com.java4coding.other module.

java-module-exports-0
 

We can export package to more than one selected client. In this case module name should be separated by coma.

module com.java4coding.app {

        exports com.java4coding.util;

        exports com.java4coding.security to com.java4coding.client, com.java4coding.other;

}

In below screen shot, we have exported com.java4coding.security package from com.java4coding.app module to both com.java4coding.client and com.java4coding.other module both. Hence now we can access Security class inside com.java4coding.other module.

java-module-exports-1
 

All Chapters
Author