JShell is an interactive tool introduced since Java 9. It is Java's first official REPL tool for creating a simple programming environment from the command line to read user input, evaluate it, and print the results.
We can create new JShell instances programmatically using the Java language. JShell and its associated API can be found under the jdk.jshell package. We can use the static method create() of the JShell class to get a new instance of JShell. The eval() method of the JShell class is used to add an expression to a JShell instance. It returns a list of events triggered by the evaluation. It is just a fragment, similar to Expression, Statement, Method, Class, Variable Declaration or import declaration. Each SnippetEvent created from the eval() method checks the output of the expression using SnippetEvent.value().
import java.util.List; import <strong>jdk.jshell</strong>.*; public class JShellTest { public static void main(String args[]) { <strong>JShell </strong>jshell = <strong>JShell.create()</strong>; <strong>List<SnippetEvent></strong> list = jshell.<strong>eval</strong>("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()); } }
<strong>Size of snippetEventList : 1 Value of the expression is : 19</strong>
The above is the detailed content of How to create JShell instance programmatically in Java 9?. For more information, please follow other related articles on the PHP Chinese website!