Sub topic 15
Using External Libraries with `--class-path`
This chapter assumes that you have a JDK 9 or later, jshell on your PATH, basic Java syntax, and some terminal experience. An external library is compiled Java code stored outside the JDK, often in a JAR file. JShell can use that code when you add its JAR to the class path.
How the class path works
The class path tells Java where to find compiled classes. With JShell, use --class-path followed by a JAR file or directory:
jshell --class-path lib/mylib.jarAfter JShell starts, import the library's public types as you would in a normal Java source file:
import com.example.text.TextTools;
TextTools.reverse("hello")The class path affects name lookup. It does not automatically import classes, so you still need an import statement unless you use the fully qualified class name.
A complete small example
The following example creates a library JAR, then starts JShell with that JAR. Run these commands in an empty directory:
mkdir -p lib src/com/example/text
cat > src/com/example/text/TextTools.java <<'EOF'
package com.example.text;
public final class TextTools {
private TextTools() {}
public static String reverse(String value) {
return new StringBuilder(value).reverse().toString();
}
}
EOF
javac -d classes src/com/example/text/TextTools.java
jar --create --file lib/text-tools.jar -C classes com/example/text/TextTools.class
jshell --class-path lib/text-tools.jarAt the jshell> prompt, use the class:
import com.example.text.TextTools;
TextTools.reverse("JShell")The result is:
$2 ==> "llehS"The JAR must contain the package directory that matches the class's package name. If the package is com.example.text, the class file belongs under com/example/text/.
Class-path separators and common errors
When you provide several locations, separate them with the platform's path separator.
| Platform | Separator | Example |
|---|---|---|
| Linux and macOS | `:` | `jshell --class-path lib/a.jar:lib/b.jar` |
| Windows | `;` | `jshell --class-path "lib\a.jar;lib\b.jar"` |
A cannot find symbol error usually means that the JAR is missing, the class path is incorrect, or the class was not imported. An illegal access error can mean that the library class or method is not public. Check the library's documentation and confirm the exact package and type name.
A library can also depend on other JAR files. Include every required location on the class path. The library's documentation normally lists these dependencies.
Exercise
How would you start JShell with lib/core.jar and lib/helpers.jar on Linux or macOS?
Show answer
Run jshell --class-path lib/core.jar:lib/helpers.jar.