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 Type | Mô tả |
|---|---|
VARIABLE | Variable declaration |
METHOD | Method declaration |
CLASS | Class declaration |
EXPRESSION_STATEMENT | Expression statement |
IMPORT | Import 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.