Sub topic 15
Using External Libraries with --class-path
This chapter assumes you can start and exit JShell, declare snippets, and use slash commands. It also assumes you know what a JAR file is and how Java packages map to directories. Everything else is explained as it comes up.
JShell sees the JDK's own classes by default. To use a third-party library or your own compiled code, you must tell JShell where the classes are. You do this with the class path, the same mechanism java and javac use.
What the class path is
The class path is a list of locations where the JVM looks for compiled classes. Each entry is one of these:
- A JAR file, such as
lib/mylib.jar. - A directory that contains
.classfiles in package-shaped subdirectories, such asclasses/.
Entries are separated by : on Linux and macOS and by ; on Windows. JShell runs your snippets in a separate JVM, called the execution engine. The class path you give JShell is applied to that JVM, so any class found there can be imported and used.
Building a small library to practice with
You can follow this chapter without downloading anything. First create a tiny library. Save this as src/demo/Greeter.java:
package demo;
public class Greeter {
public static String greet(String name) {
return "Hello, " + name + "!";
}
}Then compile it and package it into a JAR:
mkdir -p classes lib
javac -d classes src/demo/Greeter.java
jar --create --file lib/mylib.jar -C classes .javac -d classes writes classes/demo/Greeter.class. The jar command stores that file at the path demo/Greeter.class inside lib/mylib.jar.
Starting JShell with --class-path
Pass the JAR when you start the session:
jshell --class-path lib/mylib.jarNow import and use the class:
jshell> import demo.Greeter;
jshell> Greeter.greet("Ada")
$2 ==> "Hello, Ada!"The import is snippet 1, so the scratch variable for the next expression is $2. You can skip the import by writing the fully qualified name, demo.Greeter.greet("Ada").
You can also point --class-path at a directory. Here that would be jshell --class-path classes. This is handy while you are still editing a library. You recompile into classes/ and do not have to rebuild a JAR each time.
How JShell finds a class
The class path only makes classes available. You still need an import (or a fully qualified name) to use a short class name in a snippet.
Multiple entries and dependencies
Most real libraries depend on other libraries. JShell does not read Maven or Gradle metadata, so every JAR the library needs at run time must be on the class path. Join the entries with the platform separator:
jshell --class-path lib/mylib.jar:lib/helper.jarOn Windows, write lib\mylib.jar;lib\helper.jar.
If you use Maven, you can copy a project's dependencies into a directory and list them from there:
mvn dependency:copy-dependencies -DoutputDirectory=lib
ls libThen build the class path from the JAR names you see. For example, with Gson you would write jshell --class-path lib/gson-2.10.1.jar, and the library's classes under com.google.gson become available.
Changing the class path inside a session
You do not have to restart JShell to add a JAR. The /env command shows or changes the evaluation context. Run it with no arguments to see the current settings:
jshell> /env
| --class-path lib/mylib.jarTo add or replace the class path, give it the new value:
jshell> /env --class-path lib/mylib.jar:lib/helper.jar
| Setting new options and restoring state.The message says "restoring state" because JShell restarts the execution JVM and replays your existing snippets. This has consequences:
- Variables are recomputed by running their initializers again. If an initializer has side effects, such as printing, writing a file, or reading a counter, those effects happen again.
- Values you built up by mutation are lost. For example, a
Listthat you filled withaddcalls comes back with only its initializer's contents. - Snippets that failed before because a class was missing may now compile.
The /reset command accepts the same options. It also discards all snippets, so it gives you a clean session on the new class path. Use /env when you want to keep your work and /reset when you want to start over.
Where each option applies
| Way to set the class path | When to use it | Effect on existing snippets |
|---|---|---|
| `jshell --class-path ...` at startup | Beginning a session that needs a library | None, the session is new |
| `/env --class-path ...` | Adding a JAR mid-session | Snippets are replayed on a new JVM |
| `/reset --class-path ...` | Switching to a different library set | All snippets are discarded |
Common errors
Package does not exist. If you forget the option, or the path is wrong, the import fails with a message like this:
jshell> import demo.Greeter;
| Error:
| package demo does not exist
| import demo.Greeter;
| ^---------^Check the path first. A relative path such as lib/mylib.jar is resolved against the directory where you started jshell, not the directory of any script. Check that the file exists with ls. Check that the package name in the import matches the directory layout inside the JAR; jar --list --file lib/mylib.jar shows it.
Class is not public. JShell's snippets live in their own package, so they can use only public classes and public members of your library. A package-private Greeter or a non-public method will fail with an access error.
Classes in the default package. A class compiled without a package line cannot be imported by name from another package, and JShell snippets are in a package. Put library classes in a named package.
Stale classes. The execution JVM loads a class once. If you recompile a class in a directory that is on the class path, the running session keeps the old version. Run /env --class-path classes again, or /reset, to load the new one.
Wrong Java version. A JAR compiled for a newer Java release than your JDK fails with an UnsupportedClassVersionError. Run jshell --version and compare it with the version the library requires.
When this is the right tool
Loading a JAR into JShell is a good way to explore an unfamiliar API. You can call methods, inspect return values, and see exceptions without writing a main method or a build file. It is not a replacement for a build tool. JShell does not resolve dependencies, so for anything with a long dependency tree, let Maven or Gradle produce the class path and paste the result.
Exercise
You start jshell --class-path lib/mylib.jar, create a variable List<String> items = new ArrayList<>(), and add three strings to it with items.add(...). You then run /env --class-path lib/mylib.jar:lib/helper.jar. What does items contain afterwards, and why?
Show answer
It is empty. /env restarts the execution JVM and replays your snippets. The replay re-runs the declaration new ArrayList<>() but not the earlier items.add(...) calls, because those were not saved as variable initializers. Mutations made after the declaration are lost.
Exercise
A teammate's import demo.Greeter; fails with "package demo does not exist", but the JAR file exists. Name two things to check.
Show answer
First, check that the JAR path is correct relative to the directory where jshell was started, and that it was passed with --class-path or /env --class-path. Second, check that the package inside the JAR really is demo, for example with jar --list --file lib/mylib.jar. A missing dependency JAR or a non-public class is also possible.