Home > Java > javaTutorial > body text

How to create JShell instance programmatically in Java 9?

WBOY
Release: 2023-09-05 19:05:02
forward
1084 people have browsed it

如何在Java 9中以编程方式创建JShell实例?

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().

Example

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());
   }
}
Copy after login

Output

<strong>Size of snippetEventList : 1
Value of the expression is : 19</strong>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template