How do you load an external file in JShell?

2k Views Asked by At

JShell is the interactive REPL command line for Java.

If I have a Java class with some methods that I would like to play around with interactively in a .java file, how do I load that file in?

Let's say I have the file HelloWorld.java:

class HelloWorld
{
    public static void main(String[] argsv)
    {
    }

    public static void doStuff()
    {
        System.out.println("Hello world");
    }
}

and I'd like to load up JShell and be able to call the doStuff() method from the command line. How do I do that?

Starting JShell with the file name as $ JShell HelloWorld.java didn't work. Nor classfile. I still get the error cannot find symbol | symbol: variable HelloWorld from JShell. Using the /open <filename> command gave same result.

2

There are 2 best solutions below

1
On BEST ANSWER

Unable to reproduce: The problem described in the question ("didn't work") is not reproducible, since it's working without issue.

Here is a Minimal, Reproducible Example with the working steps, testing on Java 9 and Java 14.

First, to verify the content of the Java source file:

C:\Temp>type HelloWorld.java
class HelloWorld
{
    public static void main(String[] argsv)
    {
    }

    public static void doStuff()
    {
        System.out.println("Hello world");
    }
}

We can run that with JShell from Java 9, loading file using command-line:

C:\Temp>jshell HelloWorld.java
|  Welcome to JShell -- Version 9.0.4
|  For an introduction type: /help intro

jshell> HelloWorld.doStuff()
Hello world

As can be seen, the Java source file is loaded just fine, and the static method is called without issue.

We can also run that with JShell from Java 14, loading file using /open command:

C:\Temp>jshell
|  Welcome to JShell -- Version 14
|  For an introduction type: /help intro

jshell> HelloWorld.doStuff()
|  Error:
|  cannot find symbol
|    symbol:   variable HelloWorld
|  HelloWorld.doStuff()
|  ^--------^

jshell> /open HelloWorld.java

jshell> HelloWorld.doStuff()
Hello world

We first tried to run before the /open command, to prove that HelloWorld did not exist, i.e. proving that it is the /open command that declares the class.

0
On

I was having a similar issue to this but in my case for whatever reason the class wouldn't load via the /open command unless I removed public from the class declaration. I don't know if this was do to a bug in my version of jshell (11.0.2 running on MacOSX Catalina), or it's something specific about jshell itself.