Sub topic 17
Embedding JShell with the jdk.jshell API
This chapter assumes you have used the jshell tool (snippets, slash commands, forward references) and can write ordinary Java with try-with-resources, streams and List. You need JDK 9 or later.
The jshell command is a small front end. The evaluation engine is a public API in the jdk.jshell module, so your own Java program can use the same engine. Typical uses are teaching tools, notebook-style editors, and applications that let users type short Java expressions.
This is a small topic in the tutorial. The goal is to know what the API offers and where its edges are.
What the API gives you
The jshell tool does three jobs: it reads input, evaluates it, and prints feedback. The API covers only the evaluation job. Reading and printing stay with your code.
| Piece | Role |
|---|---|
| `JShell` | One session. It holds variables, methods, classes and imports. |
| `JShell.Builder` | Configures a session before it starts (output streams, options). |
| `Snippet` | One unit of input after parsing. Subclasses include `VarSnippet`, `MethodSnippet`, `TypeDeclSnippet`, `ImportSnippet` and `ExpressionSnippet`. |
| `SnippetEvent` | A report that a snippet changed state. |
| `SourceCodeAnalysis` | Splits raw text into snippets and offers completion suggestions. |
A JShell object is AutoCloseable. Closing it shuts down the separate Java process that runs your snippets, so use try-with-resources.
Evaluating one snippet
eval(String) takes exactly one complete snippet and returns a List<SnippetEvent>. It does not throw for ordinary Java errors such as a type mismatch or a runtime exception. Those are reported through the events.
import java.util.List;
import jdk.jshell.EvalException;
import jdk.jshell.JShell;
import jdk.jshell.SnippetEvent;
public class EmbedDemo {
public static void main(String[] args) {
try (JShell js = JShell.create()) {
run(js, "int x = 10;");
run(js, "x * 2");
run(js, "int half(int n) { return n / 2; }");
run(js, "int twice(int n) { return quarter(n) * 4; }");
run(js, "int quarter(int n) { return n / 4; }");
run(js, "twice(40)");
run(js, "Integer.parseInt(\"abc\")");
run(js, "int y = \"text\";");
}
}
static void run(JShell js, String code) {
List<SnippetEvent> events = js.eval(code);
for (SnippetEvent e : events) {
System.out.print(e.snippet().kind() + " " + e.status()
+ " value=" + e.value());
if (e.exception() instanceof EvalException ee) {
System.out.print(" threw=" + ee.getExceptionClassName());
}
System.out.println();
}
}
}Compile and run it with javac EmbedDemo.java and then java EmbedDemo. No extra flags are needed, because jdk.jshell is resolved by default. The output is:
VAR VALID value=10
EXPRESSION VALID value=20
METHOD VALID value=null
METHOD RECOVERABLE_DEFINED value=null
METHOD VALID value=null
METHOD VALID value=null
EXPRESSION VALID value=40
EXPRESSION VALID value=null threw=java.lang.NumberFormatException
ERRONEOUS REJECTED value=nullSome details of this output are worth noting.
- The
value()of an event is aStringrendering of the result, ornullwhen there is no value. - Defining
quarterproduces two events. The first is forquarteritself. The second reports thattwice, which was waiting on it, moved fromRECOVERABLE_DEFINEDtoVALID. This is the forward-reference behaviour you saw in the tool, delivered as data. - A runtime exception leaves the status
VALID. You detect the failure withexception(), notstatus(). - A compile error gives status
REJECTED. The snippet kind isERRONEOUSwhen JShell cannot even classify it.
How a snippet moves through states
The status values form a small state machine. A snippet can change status later, when a different snippet it depends on is declared, replaced or dropped.
RECOVERABLE_DEFINED is what you saw for twice. The method exists but cannot run yet. RECOVERABLE_NOT_DEFINED applies to declarations that cannot be created at all until the missing piece appears, such as a class that extends an unknown class.
Feeding multi-line input with SourceCodeAnalysis
If you pass eval text that holds two snippets, or half of one, it throws IllegalArgumentException. A real front end must split the input first. SourceCodeAnalysis.analyzeCompletion does this. It returns the first complete snippet in source() and the unread text in remaining().
import jdk.jshell.JShell;
import jdk.jshell.SourceCodeAnalysis;
public class SplitDemo {
public static void main(String[] args) {
String input = "int a = 3; int b = 4\na + b";
try (JShell js = JShell.create()) {
SourceCodeAnalysis analysis = js.sourceCodeAnalysis();
String rest = input;
while (!rest.isBlank()) {
var info = analysis.analyzeCompletion(rest);
if (!info.completeness().isComplete()) {
System.out.println("Incomplete input: " + rest.strip());
break;
}
js.eval(info.source()).forEach(e ->
System.out.println(e.snippet().source().strip()
+ " -> " + e.value()));
rest = info.remaining();
}
}
}
}The output is:
int a = 3; -> 3
int b = 4; -> 4
a + b -> 7Note that int b = 4 had no semicolon. The completeness value COMPLETE_WITH_SEMI means the analyzer added one for you in source(). This is the same optional-semicolon rule the tool uses.
When isComplete() is false, a front end such as the jshell tool shows a continuation prompt and waits for more lines. analysis.completionSuggestions(...) powers tab completion in the same way.
Inspecting session state
The slash commands you know have API equivalents.
| Tool command | API call |
|---|---|
| `/vars` | `js.variables()` returns a `Stream<VarSnippet>`; `js.varValue(v)` gives the value as text |
| `/methods` | `js.methods()` |
| `/types` | `js.types()` |
| `/imports` | `js.imports()` |
| `/list` | `js.snippets()` |
| `/drop name` | `js.drop(snippet)` |
Commands that are about the terminal, such as /edit, /set feedback and /open, have no API equivalent. Your program implements that behaviour itself.
For a rejected snippet, js.diagnostics(snippet) returns a stream of Diag objects. Each has getMessage(Locale), getStartPosition() and isError(), so you can show a precise error to a user.
Configuring the session
Use the builder when the defaults are not enough.
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import jdk.jshell.JShell;
public class BuilderDemo {
public static void main(String[] args) {
var captured = new ByteArrayOutputStream();
try (JShell js = JShell.builder()
.out(new PrintStream(captured))
.err(new PrintStream(captured))
.build()) {
js.eval("System.out.println(\"from the snippet\")");
}
System.out.print("Captured: " + captured);
}
}This prints Captured: from the snippet. Without the builder, snippet output goes to your own System.out.
The builder also accepts compilerOptions(...) and remoteVMOptions(...). Use js.addToClasspath(path) to make a jar visible, which matches --class-path in the tool.
Gotchas
- Untrusted input is not sandboxed. A snippet can read files, open sockets and call
System.exit. Do not expose an embedded JShell to untrusted users without OS-level isolation. - A runaway snippet blocks
eval. Calljs.stop()from another thread to interrupt it. - Events are the source of truth. Check
status(),exception()anddiagnostics, not only the printed output. - Always close the session. An unclosed
JShellleaves its helper process running.
Exercise
You call js.eval("Integer.parseInt(\"abc\")") and the returned event has status VALID. How do you tell that the snippet failed, and why is the status not REJECTED?
Show answer
Check event.exception(). It holds an EvalException naming java.lang.NumberFormatException. The status is VALID because the code compiled and ran, so the failure happened at run time. REJECTED is only for snippets that fail to compile.
Exercise
Why does js.eval("int a = 1; int b = 2;") throw IllegalArgumentException, and what should a front end call first?
Show answer
eval accepts exactly one complete snippet, and this text holds two. The front end should call js.sourceCodeAnalysis().analyzeCompletion(text) in a loop, evaluating each source() and continuing with remaining() until the text is used up.