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.
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:
We can run that with JShell from Java 9, loading file using command-line:
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:We first tried to run before the
/open
command, to prove thatHelloWorld
did not exist, i.e. proving that it is the/open
command that declares the class.