这篇博文以我的我的主要 Java 9 特性 博文为基础,更深入地研究了这些特性。在这里,我们将向您展示如何在五分钟内学会 jshell,并提升您的 Java 9 开发体验。
假设您已经下载,并安装了 Java 9,那么您可以通过键入以下命令启动 shell:
jshell
或者如果你想要冗长 -
C:\jdk9TestGround>jshell -v | Welcome to JShell -- Version 9 | For an introduction type: /help intro jshell>
只需键入变量,带或不带分号 –
jshell> int i = 1; i ==> 1 | created variable i : int
未分配的值会自动分配给以 $ 开头的变量 –
jshell> "Hello World" $1 ==> "Hello World" | created scratch variable $1 : String
这意味着我们可以稍后重用该值 -
jshell> System.out.println($1); Hello World
jshell 的下一步是使用控制流(for、if、while、...)。我们可以通过输入我们的条件来做到这一点,对每一行使用 return –
jshell> if ("Hello World".equals($1)) { ...> System.out.println("Woohoo my if condition works"); ...> } Woohoo my if condition works
一个快速提示是使用 TAB 来完成代码
我们可以像Flow control一样声明一个方法,然后按
对于每一行 -
jshell> String helloWorld() { ...> return "hello world"; ...> } | created method helloWorld()
然后调用它——
jshell> System.out.println(helloWorld()); hello world
我们还可以更改 shell 中的方法,并让方法调用尚未定义的方法——
jshell> String helloWorld() { ...> return forwardReferencing(); ...> } | modified method helloWorld(), however, it cannot be invoked until method forwardReferencing() is declared | update overwrote method helloWorld()
现在我们修复方法 -
jshell> String forwardReferencing() { ...> return "forwardReferencing"; ...> } | created method forwardReferencing() | update modified method helloWorld()
我们也可以在jshell中定义类——
jshell> class HelloWorld { ...> public String helloWorldClass() { ...> return "helloWorldClass"; ...> } ...> } | created class HelloWorld
并分配和访问它们——
/env
现在我们已经掌握了基础知识,这里有一些快速命令 –
标签 | 代码补全 |
/变量 | 当前shell中的变量列表 |
/方法 | 当前shell中的方法列表 |
/列表 | jshell会话中的所有代码片段 |
/导入 | shell 中的当前导入 |
/方法 | 当前shell中的方法列表 |
/类型 | shell 中定义的当前类,在上面的例子中我们会看到“class HelloWorld” |
/编辑 | 允许您在编辑器中编辑会话(默认为 JEditPad) |
/退出 | 关闭会话 |
标签2: Java教程地址:https://www.cundage.com/article/jcg-jshell-five-minutes.html