概述
- JShell 在 JDK 9 中正式发布
- JShell API 和工具提供了一种在 JShell 状态下交互式评估 Java 编程语言的声明、语句和表达式的方法
- JShell 的状态包括不断发展的代码和执行状态
- 为了快速调查和编码,语句和表达式不需要出现在方法中,变量和方法也不需要出现在类中
- JShell 在验证简单问题时,比 IDE 更高效
启动 JShell
1 2 3 4 5
| $ jshell | Welcome to JShell -- Version 17.0.9 | For an introduction type: /help intro
jshell>
|
详细模式 - 提供更多的反馈结果,观察更多细节
1 2 3 4 5
| $ jshell -v | Welcome to JShell -- Version 17.0.9 | For an introduction type: /help intro
jshell>
|
退出 JShell
1 2 3 4 5 6
| $ jshell -v | Welcome to JShell -- Version 17.0.9 | For an introduction type: /help intro
jshell> /exit | Goodbye
|
JShell 命令
语句
立即执行
1 2 3 4 5 6 7 8
| $ jshell -v | Welcome to JShell -- Version 17.0.9 | For an introduction type: /help intro
jshell> System.out.println("Helllo, World"); Helllo, World
jshell>
|
声明
可覆盖
- JShell 支持变量的重复声明
- JShell 是一个有状态的工具,可以很好地处理多个有关联的语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| $ jshell -v | Welcome to JShell -- Version 17.0.9 | For an introduction type: /help intro
jshell> String language = "Rust"; language ==> "Rust" | created variable language : String
jshell> String ok = switch(language) { ...> case "Rust" -> "Yes"; ...> default -> "No"; ...> }; ok ==> "Yes" | created variable ok : String
jshell> System.out.println(ok); Yes
jshell>
jshell> language = "Go" language ==> "Go" | assigned to language : String
jshell> ok = switch(language) { ...> case "Rust" -> "Yes"; ...> default -> "No"; ...> }; ok ==> "No" | assigned to ok : String
jshell> System.out.println(ok); No
|
为了方便评估,可以使用 JShell 运行变量的重复声明和类型变更
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| $ jshell -v | Welcome to JShell -- Version 17.0.9 | For an introduction type: /help intro
jshell> String language = "Rust"; language ==> "Rust" | created variable language : String
jshell> language = "Go"; language ==> "Go" | assigned to language : String
jshell> int language = 1; language ==> 1 | replaced variable language : int | update overwrote variable language : String
jshell> language = 2; language ==> 2 | assigned to language : int
|
在可编译的代码中,在一个变量的作用域内,不允许重复声明,也不允许改变类型
表达式
- 在 Java 程序中,语句是最小的可执行单位,而表达式并不能单独存在
- JShell 支持表达式的输入
1 2 3
| $ jshell> 1+1 $1 ==> 2 | created scratch variable $1 : int
|
可以直接评估表达式,不再需要依附于一个语句
1 2 3 4 5 6 7
| $ jshell> "Hello, world" == "Hello, world" $2 ==> true | created scratch variable $2 : boolean
jshell> "Hello, world" == new String("Hello, world") $3 ==> false | created scratch variable $3 : boolean
|