This quick tutorial is going to cover how to import the external library into Java 9 JShell.
1. Setting The Class Path For Java 9 JShell
1.1. Start Java 9 JShell With –class-path Option
To import the external library into Java 9 JShell, at first, we will need to set the class path for JShell session. After that, we can use the external code that is accessible through the class path in our JShell session.
To set class path for Java 9 JShell session in the command line, we can use the syntax as follows:
1 |
% jshell --class-path myOwnClassPath |
For example, to set class path for JShell session to two libraries eclipse-collections-9.0.0.jar and gson-2.8.1.jar:
1 |
jshell -class-path /home/rio/libs/eclipse-collections-9.0.0.jar:/home/rio/libs/gson-2.8.2.jar |
1.2. Using The /env Command
If we’re working on an opening JShell session, and we want to set class path for it, we can use the /env command with the following syntax:
1 |
jshell> /env --class-path path |
For example, to set class path to the above libraries:
1 |
/env -class-path /home/rio/libs/gson-2.8.2.jar:/home/rio/libs/eclipse-collections-9.0.0.jar |
To learn more about Java 9 JShell, please visit Java 9 JShell Cheat Sheet
1.3. Using The CLASSPATH Variable
Another option for us set class path for Java 9 JShell to use the CLASSPATH variable. This way will allow us to set class path to all jars in a directory, for example:
1 |
CLASSPATH=/home/rio/libs/* jshell |
We have set the CLASSPATH variable to the /home/rio/libs where contains all our jar files, and in the JShell, we can access and import all classes contained in those jars.
2. Import The External Library Into Java 9 JShell
After that, we can import classes included in those libraries by using the import statement to use, for example:
3. Summary
The tutorial has illustrated us how to import the external library into Java 9 JShell. Before doing that, we will need to set class path for JShell.
Below are other Java 9 related tutorial for your references:
Java 9 JShell – Execute And Exit A Script
Create Immutable Lists In Java 9 By Static Factory Methods
Private Interface Methods In Java 9
Using The InputStream.transferTo() To Copy Streams In Java 9
Java 9 – New Methods Of The Optional Class