Java 9 REPL (JShell)

来源:这里教程网 时间:2026-02-17 21:20:40 作者:

Java 9 REPL (JShell)

REPL代表Read-Eval-Print Loop。有了JShell,Java也具备了REPL功能。使用REPL,我们可以编写和测试基于Java的逻辑,而无需使用javac进行编译,并直接查看计算结果。

运行JShell

打开命令提示符并输入jshell。

$ jshell|  Welcome to JShell -- Version 9-ea|  For an introduction type: /help introjshell>

查看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+11 ==> 4jshell> 13%72 ==> 6jshell> 22 ==> 6jshell>

在JShell中创建和使用函数

创建一个名为doubled()的函数,接受一个整数并返回它的两倍值。

jshell> int doubled(int i){ return i*2;}|  created method doubled(int)jshell> doubled(6)$3 ==> 12jshell>

退出JShell

输入/exit。

jshell> /exit| Goodbye

相关推荐