How to import external libraries in JShell in Java 9?


JShell is an interactive tool to learn Java language and prototyping Java code. JShell does the work by evaluating the commands that user types into it. This tool works on the principle of REPL (Read-Evaluate-Print-Loop).

By default, JShell automatically imports a few useful java packages when the JShell session is started. We can type the command /imports to get a list of all these imports.

jshell> /imports
| import java.io.*
| import java.math.*
| import java.net.*
| import java.nio.file.*
| import java.util.*
| import java.util.concurrent.*
| import java.util.function.*
| import java.util.prefs.*
| import java.util.regex.*
| import java.util.stream.*
| import javax.mail.internet.InternetAddress


We can also import external libraries in JShell by using the below steps:

If we want to create an InternetAddress object that resides in the javax.mail.internet package, then we need to import that package in JShell.

jshell> import javax.mail.internet.InternetAddress
| Error:
| package javax.mail.internet does not exist
| import javax.mail.internet.InternetAddress;
| ^---------------------------------^


In the above, just importing the class doesn't work because the package is unknown to the classpath. We need to add jars or class files to classpath by using the command: "/env –class-path <jars, class files>"

jshell> /env --class-path \Users\user\mail-1.4.7.jar
| Setting new options and restoring state.

jshell> import javax.mail.internet.InternetAddress


Finally, we can create an InternetAddress object by using below

jshell> InternetAddress from = new InternetAddress("a@a")
from ==> a@a

Updated on: 24-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements