如何在JShell中运行作为片段添加的整个Java文件?

我尝试安装JDK 9 Early access version 172来玩JShell。 当我尝试打开一个简单的java文件并在将其添加为片段后执行它时,它只显示了修改后的类Test并增加了片段编号。 你能帮我理解我哪里出错了吗?

| Welcome to JShell -- Version 9-ea | For an introduction type: /help intro jshell> /open G:\kavitha\Test.java jshell> /list 1 : public class Test{ public static void main(String[] args){ int i = 1; int j = 2; System.out.println("Sum of 1 and 2 is : " + (i+j)); } } jshell> /1 public class Test{ public static void main(String[] args){ int i = 1; int j = 2; System.out.println("Sum of 1 and 2 is : " + (i+j)); } } | modified class Test jshell> /list 2 : public class Test{ public static void main(String[] args){ int i = 1; int j = 2; System.out.println("Sum of 1 and 2 is : " + (i+j)); } } 

/open只加载文件,之后你必须告诉jshell你想要执行什么。

例:

 jshell> /open Test.java jshell> /list 1 : class Test { public static void main(String[] args) { System.out.println("Hello Kavitha"); } int rollDice() { return 1 + (int)(6 * Math.random()); } } jshell> Test.main(new String[0]) Hello Kavitha jshell> new Test().rollDice() $3 ==> 3 

这里我已经执行了main方法,但我也可以根据需要使用加载的类,创建新实例,调用方法等。

快捷方式/重新运行该ID的代码段。 在您的情况下,代码片段1仅加载该类并且不执行任何操作,因此通过执行/1您重新加载相同的类,同样不再执行它。

运行上面的示例后, /2将重新运行main方法,并且/3将重新掷骰子:

 jshell> /3 new Test().rollDice() $4 ==> 1 jshell> /3 new Test().rollDice() $5 ==> 6 jshell> /3 new Test().rollDice() $6 ==> 2 

附录: /open &compilation,类加载,类初始化

(试图澄清为什么 /open没有执行你的类的主要方法,并表明它是有道理的)

当您/open文件时,JShell将添加文件的内容, 就像您在shell中键入它一样

然后它将编译代码段,但如果有的话,它不会初始化类。

(我不确定是否会加载类,这是初始化之前的步骤,很难说,看到这篇文章试图探索JShell的内部,它展示了如何翻译JShell中的类名称用户,以及尝试查看已加载类列表的失败 – 但这比编译和初始化更重要

如果我打开包含以下内容的SnippetWithError.txt

 System.out.println("Hey") class Foo { int n=33; } bar 

(是的,它不需要是一个java文件,它实际上是你在shell中包含的一堆文本用于评估)

 jshell> /open SnippetWithError.txt Hey | Error: | cannot find symbol | symbol: variable bar | bar | ^-^ 

看到它打印“嘿”,它包括类Foo

 jshell> new Foo().n $2 ==> 33 

因此,JShell在你/open编译 ,它执行语句,但如果某些语句是类或方法声明,它不会执行那些,它甚至不会初始化类。

请参阅下面如何将导入计入历史记录中的单独语句,然后类声明在其自己的语句中(#3):

 jshell> /open HasStaticInitBlock.java jshell> /list 1 : import java.time.Duration; 2 : import java.time.Instant; 3 : class HasStaticInitBlock { static Instant t0 = Instant.now(); static { System.out.println("Class initialized at " + t0); } static Duration timeSinceInit() { return Duration.between(t0, Instant.now()); } } jshell> HasStaticInitBlock.timeSinceInit() Class initialized at 2017-06-07T06:49:06.746185Z $4 ==> PT0.040414S jshell> HasStaticInitBlock.timeSinceInit() $5 ==> PT2.343019S 

只在需要时才执行类初始化。