JDK Tool Access from JShell - Sip of Java

The JShell Tool, a REPL originally added in JDK 9, has been updated in JDK 21 to provide better access to JDK tools. Let’s take a look!

The TOOLING Script

Accessing JDK tools from JShell requires loading the new TOOLING script. It can be loaded on JShell initialization with the following command:

$ jshell TOOLING

Or loaded from within JShell with the /open command like below:

jshell> /open TOOLING

Using JDK Tools in JShell

The TOOLING script gives access to the following JDK tools:

  • jar
  • javac
  • javadoc
  • javap
  • jdeps
  • jmod
  • jlink
  • jpackage

The tools are loaded as methods in JShell, and the type of argument(s) the tool will take will vary. In the example below, javap takes a Class argument:

jshell> [tool-name](Object args…)

jshell> interface Empty {}

jshell> javap(Empty.class)

However, jar would take an array of String:

jshell> jar("--create", \
"--file=target/HelloWorld-jshell.jar", \ 
"--main-class=my.org.HelloWorld",\ "my/org/HelloWorld.class")

Advantages of Using JShell

An advantage of using JDK tools from JShell is that JShell is platform agnostic and will handle things like file path conversions, so this command using jar would work on Linux, macOS, and Windows:

jshell> jar("--create", \
"--file=target/HelloWorld-jshell.jar", \ 

Additional Reading

JShell Tooling - Christian Stein

JDK-8306560 - JBS Issue

Happy coding!