Java 9 REPL (JShell)
Java 9 REPL (JShell)
REPL代表Read-Eval-Print循环。有了JShell,Java有REPL能力。使用REPL,我们可以在不使用javac编译的情况下编写和测试基于Java的逻辑,并直接看到计算结果。
运行JShell
打开命令提示符并键入jshell。
$ jshell | Welcome to JShell -- Version 9-ea | For an introduction type: /help intro jshell>
查看JShell命令
当jshell运行后,输入/help显示更多帮助。
jshell> /help | Type a Java language expression, statement, or declaration. | Or type one of the following commands: | /list [<name or id>|-all|-start] | list the source you have typed | /edit <name or id> | edit a source entry referenced by name or id | /drop <name or id> | delete a source entry referenced by name or id | /save [-all|-history|-start] <file> | Save snippet source to a file. | /open <file> | open a file as source input | /vars [<name or id>|-all|-start] | list the declared variables and their values | /methods [<name or id>|-all|-start] | list the declared methods and their signatures | /types [<name or id>|-all|-start] | list the declared types | /imports | list the imported items
运行JShell命令
jshell运行后,可以键入/ imports并查看使用过的导入。
jshell> /imports | import java.io.* | import java.math.* | import java.net.* | import java.nio.file.* | import java.util.* | import java.util.concurrent.* | import java.util.function.* | import java.util.prefs.* | import java.util.regex.* | import java.util.stream.* jshell>
在JShell中运行计算器。
尝试在JShell中运行简单的计算。
jshell> 3+1 $1 ==> 4 jshell> 13%7 $2 ==> 6 jshell> $2 $2 ==> 6 jshell>
在JShell中创建和使用函数
创建一个函数doubled()来取int并返回其双倍值。
jshell> int doubled(int i){ return i*2;} | created method doubled(int) jshell> doubled(6) $3 ==> 12 jshell> Exiting JShell Type /exit. jshell> /exit | Goodbye