Sub topic 17
Embedding JShell with the `jdk.jshell` API
Assume that you have a JDK 9 or later, basic Java syntax, and experience compiling and running Java programs. This chapter focuses on the programmatic API, not on typing commands directly into the jshell terminal.
The jdk.jshell module lets a Java program create and control a JShell session. Your program can submit Java snippets, inspect their status, collect results, and report diagnostics. This is useful for teaching tools, notebooks, IDE features, and automated experiments.
Creating a session
Create a session with JShell.builder().build(). JShell implements AutoCloseable, so use a try-with-resources statement. Closing the session releases its execution resources.
import jdk.jshell.JShell;
import jdk.jshell.SnippetEvent;
import jdk.jshell.Snippet.Status;
public class EmbeddedJshellDemo {
public static void main(String[] args) {
try (JShell shell = JShell.builder().build()) {
evaluate(shell, "int x = 6 * 7;");
evaluate(shell, "x + 8;");
}
}
private static void evaluate(JShell shell, String source) {
for (SnippetEvent event : shell.eval(source)) {
System.out.println("Source: " + event.snippet().source());
System.out.println("Status: " + event.status());
if (event.status() == Status.VALID && event.value() != null) {
System.out.println("Value: " + event.value());
}
}
}
}Compile and run the program:
javac --add-modules jdk.jshell EmbeddedJshellDemo.java
java --add-modules jdk.jshell EmbeddedJshellDemoThe second snippet sees x, because both snippets run in the same session. Its value is 50.
Understanding events and diagnostics
eval returns a list of SnippetEvent objects. An event describes what happened to a submitted snippet. Its status() can indicate states such as VALID, RECOVERABLE_NOT_DEFINED, or REJECTED. The value() method contains the textual result of an expression when one exists.
A rejected snippet does not automatically terminate the session. Inspect diagnostics when you need an explanation:
var events = shell.eval("int broken = ;");
for (SnippetEvent event : events) {
shell.diagnostics(event.snippet()).forEach(diagnostic ->
System.out.println(diagnostic.getMessage(null)));
}The API also reports updates caused by a declaration. For example, redefining a method can produce events for the new declaration and declarations that depend on it.
When to use the API
Use the API when another Java application needs interactive evaluation. For a one-off experiment, the command-line jshell tool is simpler. For production business logic, compile ordinary Java classes instead. JShell evaluates snippets dynamically, so it adds runtime complexity and should not replace normal compilation, testing, or access control.
Exercise
Why does the second call to shell.eval see the variable x?
Show answer
Both snippets execute inside the same JShell object, which preserves declarations as session state.