I was trying to understand jshell and fumbled to import external library. As of date I couldn't see any suggestion/solution for this.
Can someone please let me know if already figured this out.
Copy the jar file to the libs folder. Here, you can see our added jar file under the libs folder. Right-click on the jar file and select Add As Library. The library is successfully added to our project.
Note: the Java language defines that the java. lang package in automatically imported so this does not need to be explicitly imported. To set the startup script use /set start : jshell> /set start mystartup.
JShell is a Java read-eval-print loop which was first introduced in the JDK 9. It is tracked by JEP 222 jshell: The Java Shell (Read-Eval-Print Loop).
I tried with 9 Build 162 Linux 64-bit
with preparation:
guava-19.0.jar
and commons-lang3-3.4.jar
to
/opt/libs
The following options are available:
Specify CLASSPATH
environment variable:
$> CLASSPATH="/opt/libs/commons-lang3-3.4.jar:/opt/libs/guava-19.0.jar" bin/jshell
Specify classpath with jshell option:
$> bin/jshell --class-path /opt/libs/guava-19.0.jar:/opt/libs/commons-lang3-3.4.jar
Configure evaluation context within jshell session with command /env
, /reset
or /reload
(these commands are different, you can check out with its help info), take /env
as example:
jshell> /env -class-path /opt/libs/commons-lang3-3.4.jar:/opt/libs/guava-19.0.jar
And then you're able to either import org.apache.commons.lang3.StringUtils
or import com.google.common.base.Optional;
.
Give a try and share your feedback.
Easier way in maven, see In JShell, how to import classpath from a Maven project: In your project directory, run:
mvn com.github.johnpoth:jshell-maven-plugin:1.0:run
If you have a maven pom.xml
, you can use https://github.com/bitterfox/jshell-maven-plugin. This uses all dependencies as the classpath. The plugin is not currently in maven, so you need to clone the repo: git clone https://github.com/bitterfox/jshell-maven-plugin.git
. Then,
mvn clean install
add the following to your pom.xml
:
<build>
<plugins>
<plugin>
<groupId>net.java.openjdk.shinyafox</groupId>
<artifactId>jshell-maven-plugin</artifactId>
<version>1.0-SNAPSHOT</version>
</plugin>
</plugins>
</build>
start with mvn jshell:compile
Start Jshell importing all jars from a directory
Let directory is ~/app/java/jars/
jshell --class-path $(ls -d ~/app/java/jars/* | tr '\n' ':')
If you are using Fish shell, you can set the alias in your fish config file. Here's how you can do it. In your fish config ( ~/.config/fish/config.fish ), add
alias jshell "~/.jenv/versions/12.0.1/bin/jshell --class-path (find ~/.m2/repository/ -name \"*.jar\" | tr '\n' ':')"
This will load all the jars in your class path.
Note: Change the jshell path and jars repository path accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With