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

Другие расширения