Руководство по Java 9. REPL (JShell).

В данной статье мы рассмотрим нововведение Java 9 под названием REPL (Read Eval Print Loop). Используя REPL мы имеем возможность тестировать базовую логику без использования javac компилятора и сразу видеть результат выполнения.

Для того чтобы начать работу с JShell, нам необходимо открыть терминал и выполнить следующую команду:


jshell 

В результате выполнения данной команды, мы получим следующий результат:


|  Welcome to JShell -- Version 9.0.1
|  For an introduction type: /help intro

Для просмотра доступных JShell команд, мы можем выполнить команду /help:


jshell> /help
|  Type a Java language expression, statement, or declaration.
|  Or type one of the following commands:
|  /list [|-all|-start]
|  	list the source you have typed
|  /edit 
|  	edit a source entry
|  /drop 
|  	delete a source entry
|  /save [-all|-history|-start] 
|  	Save snippet source to a file
|  /open 
|  	open a file as source input
|  /vars [|-all|-start]
|  	list the declared variables and their values
|  /methods [|-all|-start]
|  	list the declared methods and their signatures
|  /types [|-all|-start]
|  	list the type declarations
|  /imports 
|  	list the imported items
|  /exit []
|  	exit the jshell tool
|  /env [-class-path ] [-module-path ] [-add-modules ] ...
|  	view or change the evaluation context
|  /reset [-class-path ] [-module-path ] [-add-modules ]...
|  	reset the jshell tool
|  /reload [-restore] [-quiet] [-class-path ] [-module-path ]...
|  	reset and replay relevant history -- current or previous (-restore)
|  /history 
|  	history of what you have typed
|  /help [|]
|  	get information about using the jshell tool
|  /set editor|start|feedback|mode|prompt|truncation|format ...
|  	set configuration information
|  /? [|]
|  	get information about using the jshell tool
|  /! 
|  	rerun last snippet -- see /help rerun
|  / 
|  	rerun snippets by ID or ID range -- see /help rerun
|  /- 
|  	rerun n-th previous snippet -- see /help rerun
|  
|  For more information type '/help' followed by the name of a
|  command or a subject.
|  For example '/help /list' or '/help intro'.
|  
|  Subjects:
|  
|  intro
|  	an introduction to the jshell tool
|  id
|  	a description of snippet IDs and how use them
|  shortcuts
|  	a description of keystrokes for snippet and command completion,
|  	information access, and automatic code generation
|  context
|  	a description of the evaluation context options for /env /reload and /reset
|  rerun
|  	a description of ways to re-evaluate previously entered snippets

Давайте рассмотрим базовые возможности JShell.

Объявление переменных:


jshell> int i = 100;
i ==> 100

jshell> double y = 100.5;
y ==> 100.5

Просмотр всех объявленных переменных:


jshell> /vars
|    int i = 100
|    double y = 100.5

Арифметические операции:


jshell> 100 + 200
$1 ==> 300

jshell> 500-450
$2 ==> 50

jshell> 2*3
$3 ==> 6

jshell> 700/100
$4 ==> 7

jshell> 21%10
$5 ==> 1

Создание и использование методов:


jshell> int numbersMultiplication(int x, int y){return x*y;}
|  created method numbersMultiplication(int,int)

jshell> numbersMultiplication(5,7)
$7 ==> 35

Просмотр всех объявленных методов:


jshell> /methods
|    int numbersMultiplication(int,int)

Мы, также, имеем возможность увидеть пакеты и классы, которые на данный момент импортированы в JShell:


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> /exit
|  Goodbye

На этом мы заканчиваем обзор REPL (JShell).
В следующей статье мы рассмотрим понятие модульности в Java 9.