Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách tạo JShell instance lập trình (programmatically) trong Java 9

JShell (Java 9 REPL) có API dưới package jdk.jshell. Có thể tạo instance JShell programmatically, evaluate snippet, lấy kết quả.

API chính

  • JShell.create(): Static factory tạo instance JShell mới.
  • eval(String snippet): Đánh giá snippet, trả về List<SnippetEvent>.
  • SnippetEvent.value(): Lấy giá trị kết quả của expression snippet.

Ví dụ: Tạo JShell, eval biểu thức

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

Kết quả

Size of snippetEventList : 1
Value of the expression is : 19

Các SnippetEvent type

Event TypeMô tả
VARIABLEVariable declaration
METHODMethod declaration
CLASSClass declaration
EXPRESSION_STATEMENTExpression statement
IMPORTImport declaration

Ví dụ nâng cao: Đa snippet, error handling

JShell jshell = JShell.create();

// Nhiều snippet
List<SnippetEvent> events = jshell.eval("int a = 10; int b = 20; int sum = a + b;");
events.forEach(e -> System.out.println(e.snippet() + " -> " + e.value()));

// Xử lý error
List<SnippetEvent> errEvents = jshell.eval("int x = 1/0;");
errEvents.forEach(e -> {
    if (e.status() == SnippetEvent.Status.VALID) {
        System.out.println("Value: " + e.value());
    } else {
        System.out.println("Error: " + e.diagnostic());
    }
});

// Đóng JShell
jshell.close();

Ứng dụng

  • Embedded REPL trong ứng dụng (IDE, notebook, teaching tool).
  • Dynamic code evaluation / scripting engine.
  • Testing API trong runtime.
  • Build tool tùy chỉnh.

JShell API biến Java thành platform cho tooling, education, dynamic execution.