Sub topic 14
JAR files and a first look at modules
This chapter assumes you can compile and run packaged code with javac -d and java -cp, and that you know what a fully qualified class name is. It covers how compiled packages are bundled into JAR files, how those files are used on the classpath, and how the module system adds a second layer of access control above packages.
Why bundle classes into JAR files
After javac -d out, your program is a tree of .class files under out/. That tree is awkward to ship, version, or hand to someone else. A JAR (Java ARchive) file is a ZIP file that holds the same directory tree. The paths inside the JAR mirror the package structure, so com/example/shop/Main.class sits at that path inside the archive.
A JAR can also contain resources (properties files, images) and a manifest. The manifest is a text file at META-INF/MANIFEST.MF that carries metadata, such as which class has the main method.
The JDK ships a jar tool. Using the shop classes from earlier chapters, already compiled into out/:
jar --create --file shop.jar -C out .
jar --list --file shop.jar-C out . means "change to the out directory and add everything in it". The -C matters. Without it, every entry in the archive would start with out/, and the package paths would no longer match the directories. The class loader would then fail to find com.example.shop.Main.
The listing shows entries such as META-INF/MANIFEST.MF, com/example/shop/Main.class, and com/example/shop/model/Product.class. The short options jar tf shop.jar give the same listing.
Running code from a JAR
A JAR is used on the classpath exactly like a directory of classes:
java -cp shop.jar com.example.shop.MainThe launcher looks inside the JAR for the path com/example/shop/Main.class. A classpath can mix directories and JARs, separated by : on Linux and macOS and by ; on Windows. A trailing * includes every JAR in a directory:
java -cp "lib/*:out" com.example.shop.MainQuote the wildcard so the shell does not expand it. The * matches only .jar files in that directory, not subdirectories.
You can record the entry point in the manifest, so users do not need to know the class name:
jar --create --file shop.jar --main-class com.example.shop.Main -C out .
java -jar shop.jar--main-class writes a Main-Class entry into the manifest. With java -jar, the launcher ignores any -cp option and the CLASSPATH environment variable. Dependencies of an executable JAR must be named in its manifest with a Class-Path entry, or bundled in some other way.
The classpath is searched in order, and the first matching class wins. If two JARs both contain com.acme.util.Strings, the one listed first is used and the other is silently ignored. This is a common source of "works on my machine" bugs. The packages and imports compile fine, but the wrong version loads at run time.
Where packages stop being enough
Packages give you namespaces and package-private access. They have two weaknesses at scale.
- Any public class is reachable by everyone. If your library has a public class in
com.example.shop.internal, any caller can import it. Marking it public was necessary so your own other packages could use it, but now it is part of your public API whether you wanted that or not. - The classpath has no notion of dependencies. It is a flat list. Nothing checks that a required JAR is present until a
NoClassDefFoundErrorappears at run time.
Java 9 introduced modules to address both problems.
What a module is
A module is a named group of packages, plus a descriptor that states two things: which packages other modules may use, and which other modules this one needs. The descriptor is a file named module-info.java at the root of the source tree.
Here is a module descriptor for the shop code:
module com.example.shop {
exports com.example.shop.model;
}With this descriptor:
- The
modulename follows the same reverse-domain convention as package names. exports com.example.shop.modelmakes the public types in that package accessible to other modules.- Every package that is not exported, here
com.example.shop, is hidden from other modules. Even apublicclass in a hidden package cannot be imported by code outside the module.
This is called strong encapsulation. It is a new level of access control sitting above the four levels you already know.
| Access level | Who can reach the member or class |
|---|---|
| `private` | The same class |
| package-private | The same package |
| `protected` | The same package and subclasses |
| `public` in a non-exported package | Only the same module |
| `public` in an exported package | Any module that requires this one |
Two points are easy to miss. Exports are per package, not per class, and they are not recursive: exporting com.example.shop does not export com.example.shop.model. A package may also be split across modules only if the modules are not both visible to the same layer, and in practice you should treat each package as belonging to exactly one module.
Using another module
A second module declares its dependency with requires:
module com.example.app {
requires com.example.shop;
}package com.example.app;
import com.example.shop.model.Product;
public class App {
public static void main(String[] args) {
Product p = new Product("Notebook", 4.25);
System.out.println(p.getName() + " costs " + p.getPrice());
}
}The import statement is unchanged. Imports still decide how you write names in source, and requires decides whether the compiler and runtime let you see the package at all. The two work together: you need both requires for the module and import for the class (or its fully qualified name).
Assume the shop module sources are in shop-src/, with module-info.java at its root, and the app sources are in app-src/. You compile and run with the module path instead of the classpath:
javac -d out/shop shop-src/module-info.java shop-src/com/example/shop/Main.java shop-src/com/example/shop/model/Product.java
javac --module-path out/shop -d out/app app-src/module-info.java app-src/com/example/app/App.java
java --module-path out/shop:out/app --module com.example.app/com.example.app.AppThe last argument has the form module/class. On Windows, use ; between module path entries.
If App tried to import com.example.shop.Main, compilation would fail. The error says the package com.example.shop is declared in module com.example.shop, which does not export it. If you remove the requires line instead, the error says the package does not exist in any module the app reads. Both are compile-time errors, which is the point: dependency mistakes show up before you run anything.
Modular JARs
A modular JAR is a normal JAR with module-info.class at its root. You build it with the same tool:
mkdir mods
jar --create --file mods/shop.jar -C out/shop .
jar --describe-module --file mods/shop.jarThe second command prints the module name and its exports. You can then put the mods directory on the module path with --module-path mods, and the runtime treats each JAR in it as a module.
The following diagram contrasts how the two mechanisms find code.
Mixing old and new code
Most libraries are not modular, so Java defines two transitional cases.
- The unnamed module. Anything on the classpath is placed in one special module with no name. It can read every other module and exports all its packages, so legacy code keeps working.
- Automatic modules. A plain JAR placed on the module path becomes a module whose name is derived from the manifest entry
Automatic-Module-Nameor, failing that, from the file name. It exports all its packages and reads everything. This lets a modular application depend on a library that has not yet added a descriptor.
A named module cannot requires the unnamed module, so a modular application that needs a classpath-only library must put that JAR on the module path and let it become an automatic module.
Modules are not required. Most application code still runs from the classpath, and the JDK itself is modular: java.base holds java.lang and java.util, and every module implicitly requires it. That is why you never wrote requires java.base. For other JDK parts, such as java.sql, which holds java.sql.Date from the name-conflict example, a modular application must write requires java.sql;.
Common mistakes
- Running
jarwithout-C, so entries have the wrong path prefix and classes are not found. - Expecting
-cpto work together withjava -jar. The-jaroption takes over the classpath. - Forgetting that
exportsapplies to one package, not its sub-packages. - Using
:as the path separator in a Windows command, or;on Linux. - Putting
module-info.javain a package directory instead of at the source root.
Exercise
A module com.example.shop has the packages com.example.shop and com.example.shop.model, and its descriptor contains only exports com.example.shop.model;. Another module requires it and contains import com.example.shop.Main;. Does this compile? What changes if Main is declared public?
Show answer
It does not compile. Main is in com.example.shop, which is not exported, so the compiler reports that the package is declared in module com.example.shop, which does not export it. Making Main public changes nothing, because module exports are checked per package before class access modifiers apply. The fix is to add exports com.example.shop; to the descriptor.
Exercise
You built shop.jar with jar --create --file shop.jar --main-class com.example.shop.Main -C out .. A teammate runs java -cp lib/* -jar shop.jar and gets a NoClassDefFoundError for a class in lib/. Why, and how can the JAR be fixed?
Show answer
With -jar, the launcher ignores -cp, so the libraries in lib/ are never searched. Add a Class-Path entry to the JAR's manifest that lists the library JARs by relative path, or run the program with java -cp shop.jar:lib/* com.example.shop.Main instead of -jar.