Skip to content

Instantly share code, notes, and snippets.

@aman-junaid
Last active October 11, 2022 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aman-junaid/2a1f5a5b3330f716a98361b3bfe49285 to your computer and use it in GitHub Desktop.
Save aman-junaid/2a1f5a5b3330f716a98361b3bfe49285 to your computer and use it in GitHub Desktop.

Java Module example

  1. Create a project - C:\..\modulesDemo
  2. Create a folder for java files under the project - src\com.aj.modules
  3. Create a the java module file in the directory src\com.aj.modules - module-info.java
module com.aj.modules {
}
  1. Create the folder for file to be included in the module - src\com.aj.modules\com\aj\modules
  2. Create TestMain.java file
package com.aj.modules;

public class TestMain {
	
	public static void main (String args[]) {
		System.out.println("Hello modules from medium :)");
	}
}
  1. Create a folder to store the module compiled files - ../modulesDemo/mods/com.aj.modules
  2. Before compilation folder structure
../modulesDemo
      ├── mods
            └── com.aj.modules
      └── src
	    └── com.aj.modules
	    	├── module-info.java
              	└── com
                  └── aj
                    └── modules
                      └── TestMain.java
  1. Compile the module, navigate to the project folder i.e. modulesDemo, and compile the module using the command below.
javac -d mods/com.aj.modules src/com.aj.modules/module-info.java`

Command explaination-
<-d mods/com.aj.modules> - output directory
<src/com.aj.modules/module-info.java> - source directory
  1. Compile the module contents i.e. TestMain.java file. javac -d mods/com.aj.modules src/com.aj.modules/com/aj/modules/TestMain.java
  2. After the compilation you will have a project structure as below
../modulesDemo
      ├── mods
            └── com.aj.modules
              ├── module-info.class
              └── com
                └── aj
                  └── modules
                    └── TestMain.class
      └── src
            └── com.aj.modules
	      ├── module-info.java
              └── com
                └── aj
                  └── modules
                    └── TestMain.java
  1. To run the TestMain class in the module, navigate to folder /modulesDemo, the run this command-
java --module-path mods -m com.aj.modules/com.aj.modules.TestMain

Command explaination-
java --module-path <path to module, compiled> -module <module name>/<package>.<main class>

  1. Here is the output-
C:\..\modulesDemo>java --module-path mods -m com.aj.modules/com.aj.modules.TestMain
Hello modules from medium :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment