본문 바로가기

Learning

JAVA9 jshell(REPL)

JAVA9에 새로이 소개된 기능중에 하나는 jshell 프로그램이다. 


REPL

Read Evaluate Print Loop의 약자인 REPL은 간단한 콘솔 입력 프로그램을 통해 개발자가 입력한 명령어를 실행하고 바로 화면에 출력하는 실행환경을 의미한다. 많은 프로그램 언어들이 이 방식을 지원하고 있다.


JAVA9를 설치하고 'bin'디렉토리에 있는 'jshell' 프로그램을 터미널창 혹은 커맨드창에서 실행하면 된다. (JDK 9.0.4를 기준으로) 실행하면 '/help intro' 명령을 입력해보라고 한다. 아래 해당 사항 실행 및 결과이다.


home:~$ ./apps/java/jdk1.9/bin/jshell 

|  Welcome to JShell -- Version 9.0.4

|  For an introduction type: /help intro


jshell> 

jshell> /help intro

|  

|  intro

|  

|  The jshell tool allows you to execute Java code, getting immediate results.

|  You can enter a Java definition (variable, method, class, etc), like:  int x = 8

|  or a Java expression, like:  x + x

|  or a Java statement or import.

|  These little chunks of Java code are called 'snippets'.

|  

|  There are also jshell commands that allow you to understand and

|  control what you are doing, like:  /list

|  

|  For a list of commands: /help


jshell> 

jshell>


변수 선언 (자동 선언 포함)

자바 문법에 따라 값을 선언할 수 있고, 간단히 값만 입력하면 자동으로 변수가 선언된다. 그러나 '변수 = 값' 처럼 시용 하면 오류로 처리된다. 배열 선언도 같은 방식으로 동작한다.

jshell> 

jshell> 100

$1 ==> 100


jshell> int a = 101

a ==> 101


jshell> b = 102

|  Error:

|  cannot find symbol

|    symbol:   variable b

|  b = 102

|  ^


jshell>

jshell> int[] arr = new int[] { 1, 2, 3, 4, 5 }

arr ==> int[5] { 1, 2, 3, 4, 5 }


jshell> 

jshell> new int[] { 1, 2, 3, 4, 5 }

$4 ==> int[5] { 1, 2, 3, 4, 5 }


jshell> 


연산, 제어 및 함수 호출

연산은 대부분 자바문법을 따르며, 좌항이 생략되면 자동으로 임시변수에 값이 할당된다. 제어문등 긴 코드를 입력할 때 자동으로 줄바꿈이 지원된다.

jshell> System.out.println("result=" + (arr[0] + $1))

result=101


jshell> if                                <=== 엔터키

   ...> ( arr[0] == 1)                <=== 자동으로 줄바꿈 인식

   ...> { return false; }


/vars, /list, /edit

위 세개의 명령어는 코딩시 유용한데 '/help'명령어로 사용법을 확인할 수 있다. 각각의 기능은 아래와 같다.

  • /vars : 선언된 변수들을 보여준다.
  • /list : 입력된 소스코드들을 보여준다.
  • /edit : 앞서 입력한 소스코드를 수정할 수 있도록 UI를 제공해준다.

'/list' 명령어는 오류가 없는 소스코드들만 나열하는데, 만약 오류가 있는 것들도 같이 보고 싶다면 '/list -all' 하면 된다.

jshell> /vars

|    int $1 = 100

|    int a = 101

|    int[] arr = int[5] { 1, 2, 3, 4, 5 }

|    int[] $4 = int[5] { 1, 2, 3, 4, 5 }

|    PrintStream $6 = java.io.PrintStream@4cf777e8


jshell> 

jshell> /vars arr                   <=== 특정 변수 'arr' 값을 보여준다.

|    int[] arr = int[5] { 1, 2, 3, 4, 5 }


jshell> /list                          <=== 오류가 없는 코드만 보여준다.

   1 : 100

   2 : int a = 101;

   3 : int[] arr = new int[] { 1, 2, 3, 4, 5 };

   4 : new int[] { 1, 2, 3, 4, 5 }

   5 : if

       ( arr[0] == 1)

       { return false; }

   6 : System.out


jshell> /list -all                                          <=== -all 옵션

  s1 : import java.io.*;                                 <=== 's'가 붙은 것은 시작할 때 수행된 코드

  s2 : import java.math.*;

  s3 : import java.net.*;

  s4 : import java.nio.file.*;

  s5 : import java.util.*;

  s6 : import java.util.concurrent.*;

  s7 : import java.util.function.*;

  s8 : import java.util.prefs.*;

  s9 : import java.util.regex.*;

 s10 : import java.util.stream.*;

   1 : 100

   2 : int a = 101;

  e1 : b = 102                                                 <=== 'e''가 붙은 것은 오류가 발생한 코드

   3 : int[] arr = new int[] { 1, 2, 3, 4, 5 };

   4 : new int[] { 1, 2, 3, 4, 5 }

   5 : if

       ( arr[0] == 1)

       { return false; }

  e1 : if ( arr[0] == 1 ) false;

   6 : System.out

   7 : System.out.println("result=" + arr[0] + $1)

   8 : System.out.println("result=" + (arr[0] + $1))


jshell> /edit 6                     <=== /list 목록내 6항에 해당하는 코드를 편집할 수 있게 한다.


TAB

소스코드를 입력하는 도중 탭키를 누르면 입력중인 소스코드에 따라 도움을 줄 수 있는 내용을 제공해준다. 예를 들면 변수를 설명해주거나, 관련 함수들을 보여주거나 한다. 개발자가 입력한 소스코드 내용도 포함된다. 

jshell> System.out.print                     <=== 탭키를 누루면 print로 시작하는 함수들이 보여진다.

print(     printf(    println(   


jshell> System.out.      <=== 'dot' 다음에 탭키를 누루면 사용할 수 있는 함수들이 보여진다.

append(        checkError()   close()        equals(        flush()        format(        getClass()     hashCode()     

notify()       notifyAll()    print(         printf(        println(       toString()     wait(          write(         


jshell> System.out       <=== 이 경우에는 'out'에 대한 설명이 보여진다.

out   


Signatures:

System.out:java.io.PrintStream


jshell> arr                     <=== 개발자가 입력한 코드도 지원된다.

arr   


Signatures:

arr:int[]


<press tab again to see documentation>  <=== 탭을 더 누르면 추가 정보가 보여진다.


jshell> arr

arr:int[]

<no documentation found>




마치며

가장 강력한 부분은 jshell은 자바 프로그램에 내장될 수 있다는 것이다. 사용자와 상호작용이 필요한 프로그램을 제작할 때, jshell 의 REPL기능을 내장해서 이용한다면 상당히 강력한 프로그램을 만들 수 있다고 본다. 생각외로 상당히 다양하게 응용될 수 있다고 본다.