Java 9 Modules - Package private and Splitting example

[Updated: Oct 8, 2017, Created: Oct 7, 2017]

A class member without a modifier has package-private access, i.e. it is visible only within its own package. This is true even for the classes which are defined in different jars having the same package (split packages). Because of this access benefit, developers tend to create split packages (most of the time). Following example shows how Java 9 modules restricts package-private members access in split packages.

Example

A library module

This module creates a package-private class.

core-parser/src/parser/xml/XmlParserUtil.java

package parser.xml;

class XmlParserUtil {
  public static String parse(String data) {
      return "parsed data " + data;
  }
}

core-parser/src/module-info.java

module core.parser {
  exports parser.xml;
}

An application module

parser-app/src/parser/xml/AppMain.java

package parser.xml;

public class AppMain {
  public static void main(String[] args) {
      String data = XmlParserUtil.parse("test data");
      System.out.println(data);
  }
}

parser-app/src/module-info.java

module parser.app {
  requires core.parser;
}

Compiling

D:\split-packages>tree /A /F
+---core-parser
| \---src
| | module-info.java
| |
| \---parser
| \---xml
| XmlParserUtil.java
|
\---parser-app
\---src
| module-info.java
|
\---parser
\---xml
AppMain.java
D:\split-packages\core-parser>javac -d out src\module-info.java src\parser\xml\XmlParserUtil.java
D:\split-packages\parser-app>javac --module-path ../core-parser/out -d out src\module-info.java src\parser\xml\AppMain.java
src\parser\xml\AppMain.java:1: error: package exists in another module: core.parser
package parser.xml;
^
src\parser\xml\AppMain.java:5: error: cannot find symbol
String data = XmlParserUtil.parse("test data");
^
symbol: variable XmlParserUtil
location: class AppMain
2 errors

The compilation will even fail if the member (XmlParserUtil class in this example) is public instead of package private.

Running on Classpath

Let's compile the application as unnamed modules (using classpath):

D:\split-packages\parser-app>javac -cp ../core-parser/out -d out2 src\parser\xml\AppMain.java

Running:

D:\split-packages\parser-app>java -cp ../core-parser/out;out2 parser.xml.AppMain
parsed data test data

Example Project

Dependencies and Technologies Used :

  • JDK 9
Package private and Splitting Example Select All Download
  • split-packages
    • core-parser
      • src
        • parser
          • xml
    • parser-app
      • src
        • parser
          • xml

See Also