Java 9 REPL (JShell)

REPL(Read Eval Print Loop)意为交互式的编程环境。

JShell 是 Java 9 新增的一个交互式的编程环境工具。它允许你无需使用类或者方法包装来执行 Java 语句。它与 Python 的解释器类似,可以直接 输入表达式并查看其执行结果。

执行 JSHELL

  1. $ jshell
  2. | Welcome to JShell -- Version 9-ea
  3. | For an introduction type: /help intro
  4. jshell>

查看 JShell 命令

输入 /help 可以查看 JShell相关的命令:

  1. jshell> /help
  2. | Type a Java language expression, statement, or declaration.
  3. | Or type one of the following commands:
  4. | /list [<name or id>|-all|-start]
  5. | list the source you have typed
  6. | /edit <name or id>
  7. | edit a source entry referenced by name or id
  8. | /drop <name or id>
  9. | delete a source entry referenced by name or id
  10. | /save [-all|-history|-start] <file>
  11. | Save snippet source to a file.
  12. | /open <file>
  13. | open a file as source input
  14. | /vars [<name or id>|-all|-start]
  15. | list the declared variables and their values
  16. | /methods [<name or id>|-all|-start]
  17. | list the declared methods and their signatures
  18. | /types [<name or id>|-all|-start]
  19. | list the declared types
  20. | /imports
  21. | list the imported items

执行 JShell 命令

/imports 命令用于查看已导入的包:

  1. jshell> /imports
  2. | import java.io.*
  3. | import java.math.*
  4. | import java.net.*
  5. | import java.nio.file.*
  6. | import java.util.*
  7. | import java.util.concurrent.*
  8. | import java.util.function.*
  9. | import java.util.prefs.*
  10. | import java.util.regex.*
  11. | import java.util.stream.*
  12. jshell>

JShell 执行计算

以下实例执行 JShell 简单计算:

  1. jshell> 3+1
  2. $1 ==> 4
  3. jshell> 13%7
  4. $2 ==> 6
  5. jshell> $2
  6. $2 ==> 6
  7. jshell>

JShell 创建与使用函数

创建一个函数 doubled() ,将传入的整型参数乘于 2 后返回:

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

退出 JShell

输入 /exit 命令退出 jshell:

  1. jshell> /exit
  2. | Goodbye