Java 9 introduced the JShell: an interactive programming shell that can speed development.
With an IDE in hand, the obvious thing to do would be to wrap JShell so that it is available as a console window. Fortunately, IntelliJ does just that! The next obvious thing to do is to make your project code available to JShell so that you can reference classes and methods you’ve already defined. This is not as easy from purely the command line, but fortunately IntelliJ does allow us to reference code in our current project with just a couple steps
There are however a few gotchas when attempting this in IntelliJ. The rest of this post applies to IntelliJ 17.3 and later, which has direct Java 9 support.
(An aside to Gradle users, if you are using IntelliJ to create a new Java 9 project, the default version of Gradle that IntelliJ 17.3 pulls down for you is 4.0, which has known issues with Java 9. It’s best to have an existing installation of Gradle 4.3 or later when creating the project, and specify that Gradle location.)
First, when you use the menu item (“Tools” -> “JShell Console…”), type some code like “1+1”, and press the “play” button, the output console doesn’t always appear, bringing confusion about where the output is. I think sometimes you need to click the the tools menu item more than once, or use CTRL-Enter to execute your code to make the output window appear. However, once it appears, it has always been visible for me even after restarts. It just caused some initial confusion to me and others who have tried it.
Next, with the JShell console visible, Java 9 needs to be available. You don’t need to run IntelliJ on Java 9 and the project doesn’t even need to be a Java 9 project, but the Java 9 installation needs to be available to IntelliJ, and you’ll need to set the JRE of the JShell from the JRE dropdown in the JShell console. Otherwise you will get a warning that “JDK 9 or higher is needed to run JShell.”
Now, adding “1+1”, and assigning “int x=0;” is fun and everything, but JShell becomes a lot more practical when you can reference classes and methods in an existing project. The libraries that your project depends on are available to JShell if you use the default setting (at the top of the JShell console) of “Use Classpath of:” [Whole Project]. But what is REALLY useful is to reference the classes and methods defined by your actual project. To do this, you need to make the output of your project available to IntelliJ as a Library. Go to “File > Project Structure”, then in the dialog “Project Settings > Libraries” add the location of the output classes of your project as a Library. For a maven project, this might look like “project/target/classes.” With this addition in place, you should be able to import and reference the classes that your project defines, enabling you to explore your code much faster than even with TDD.
Hopefully you will enjoy using JShell in your project, whether you are on Java 9 or not!