Java 9 REPL (JShell)

Java 9 新特性 Java 9 新特性

REPL(Read Eval Print Loop)意為互動式的編程環境。

JShell 是 Java 9 新增的一個互動式的編程環境工具。它允許你無需使用類或者方法包裝來執行 Java 語句。它與 Python 的解釋器類似,可以直接 輸入運算式並查看其執行結果。

執行 JSHELL

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

查看 JShell 命令

輸入 /help 可以查看 JShell相關的命令:

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 命令

/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() ,將傳入的整型參數乘於 2 後返回:

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

退出 JShell

輸入 /exit 命令退出 jshell:

jshell> /exit
| Goodbye 

Java 9 新特性 Java 9 新特性