How to create JShell instance programmatically in Java 9?

JavaObject Oriented ProgrammingProgramming

JShell is an interactive tool introduced since Java 9. It is Java's first official REPL tool to create a simple programming environment in the command-line that reads the user's inputs, evaluates it, and prints the result.

We can able to create a new JShell instance programmatically in Java language. JShell and its associated APIs can be found under jdk.jshell package. we can get a new instance for JShell by using the static method: create() of JShell class. The eval() method of JShell class used to add an expression to JShell instance. It returns a list of events triggered by the evaluation. It is exactly one snippet like an expression, statement, method, class, variable declaration, or import statement. Each SnippetEvent created from the eval() method checked for the output of expression by using SnippetEvent.value().

Example

import java.util.List;
import jdk.jshell.*;

public class JShellTest {
   public static void main(String args[]) {
      JShell jshell = JShell.create();
      List<SnippetEvent> list = jshell.eval("int x = 7+3*4;");
      System.out.println("Size of list: " + list.size());
      System.out.println("Value of the expression is : " + list.get(0).value());
   }
}

Output

Size of snippetEventList : 1
Value of the expression is : 19
raja
Published on 04-Mar-2020 14:06:19
Advertisements