[英]How do you load an external file in JShell?
JShell is the interactive REPL command line for Java. JShell 是 Java 的交互式 REPL 命令行。
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?如果我有一个带有一些方法的 Java 类,我想在 .java 文件中以交互方式使用这些方法,我该如何加载该文件?
Let's say I have the file HelloWorld.java
:假设我有文件
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.我想加载 JShell 并能够从命令行调用
doStuff()
方法。 How do I do that?我怎么做?
Starting JShell
with the file name as $ JShell HelloWorld.java
didn't work.以
$ JShell HelloWorld.java
的文件名启动JShell
不起作用。 Nor classfile.也不是类文件。 I still get the error
cannot find symbol | symbol: variable HelloWorld
我仍然收到错误
cannot find symbol | symbol: variable HelloWorld
cannot find symbol | symbol: variable HelloWorld
from JShell. cannot find symbol | symbol: variable HelloWorld
来自 JShell 的cannot find symbol | symbol: variable HelloWorld
。 Using the /open <filename>
command gave same result.使用
/open <filename>
命令给出了相同的结果。
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.这是一个包含工作步骤的最小、可重现的示例,在 Java 9 和 Java 14 上进行测试。
First, to verify the content of the Java source file:首先,验证Java源文件的内容:
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:我们可以使用 Java 9 中的 JShell 运行它,使用命令行加载文件:
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.可以看出,Java 源文件加载得很好,并且调用
static
方法没有问题。
We can also run that with JShell from Java 14, loading file using /open
command:我们还可以使用 Java 14 中的 JShell 运行它,使用
/open
命令加载文件:
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.我们首先尝试在
/open
命令之前运行,以证明HelloWorld
不存在,即证明是/open
命令声明了类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.