简体   繁体   中英

How do you load an external file in JShell?

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 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:

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, ie proving that it is the /open command that declares the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM