Saturday, October 5, 2019

JShell in Eclipse

Java 9 introduced a new command line tool: JShell. This is a read–eval–print loop (REPL) for Java with some really nice features. For programmers I would assume writing a test is the preferred choice, but for demonstrating something (in a class room for example) this is a perfect tool if you are not using a special IDE such as BlueJ (which comes with its own REPL).
The interesting thing about running JShell inside Eclipse is to use a project's classpath. This is how to run JShell inside Eclipse out of the box (given Java >=9 and Eclipse -- I have used 2019-09 -- are installed), using the currently selected project as the base line:

  • Select "Run > External Tools > External Tools Configuration"
  • Enter the following settings:
    • Name: JShell
    • Location: /usr/bin/jshell -- or whereever your jshell command is found on your system
    • Working Directory: ${project_loc}
    • Arguments: --class-path "${project_classpath}"
You can of course change these settings according to your needs. Now, when you run the tool ("Run > External Tools > JShell" or via the toolbar item), a console view is opened with the shell. It is almost like working with JShell from command line except tab etc. is not working (instead the cursor moves around).
For people not aware of JShell, there is a very good tutorial by Robert Field, and tons of other web pages about it.
For the impatient reader, some hints:

  • Inside JShell, you have some extra commands available after a prefix "/", most notable "/help"
  • If you change anything in your code (in the Eclipse editor), this is not necessarily reflected in JShell. You need to call "/reset" first!
  • You can define methods without a class, i.e. you can define functions. Syntax is similar to methods, though.
JShell as external tool inside Eclipse
Note: There is also a rather old discussion at Stackoverflow in which the "external tool" solutions is explained as well. Apparently it seems that there were some problems fixed in the meantime, because in older posts you will find that some people had problems with this solution.



2 comments:

Anonymous said...

The correct link to Robert's tutorial is JShell Tutorial.

Jens v.P. said...

Thanks! I fixed the link in the blog (actually it was an html typo...).