Java 9 นำเสนอ REPL (Read-Evaluate-Print-Loop) tool: JShell อนุญาตให้รัน code snippets และได้ผลลัพธ์ทันที Snippet คือคำสั่งที่ใช้ Java syntax มาตรฐาน แทน single expression, statement, หรือ declaration
กฎสำหรับ JShell Tool
- Snippet ประกอบด้วย: import declarations, class declarations, method declarations, interface declarations, field declarations, statements, และ primary expressions
- Package declarations ไม่อนุญาต JShell code วางอยู่ภายใต้ transient JShell package
- Access modifiers: public, protected, private และ modifiers: final, static ไม่อนุญาตใน top-level declarations ถ้าระบุจะถูก ignore พร้อม warning
- Modifiers: default, synchronized ห้ามใช้ใน top-level declarations แต่ใช้ได้ใน nested context
- Modifier abstract อนุญาตเฉพาะใน classes เท่านั้น
- ถ้า user input ไม่สมบูรณ์ (เช่นพิมพ์แค่
System.outไม่มีprintln) JShell auto-completion API จะ prompt ขอ input เพิ่ม - ถ้า user input สมบูรณ์แต่ไม่มี semicolon JShell จะ append ให้อัตโนมัติ
ตัวอย่าง: สร้าง Class Employee ใน JShell
jshell> class Employee {
...> private String firstName;
...> private String lastName;
...> private String designation;
...> public Employee(String firstName, String lastName, String designation) {
...> this.firstName = firstName;
...> this.lastName = lastName;
...> this.designation = designation;
...> }
...> public String getFirstName() {
...> return firstName;
...> }
...> public String getLastName() {
...> return lastName;
...> }
...> public String getDesignation() {
...> return designation;
...> }
...> public String toString() {
...> return "Name = " + firstName + ", " + lastName + " | " +
...> "designation = " + designation;
...> }
...> }
| created class Employee
jshell> Employee emp = new Employee("Sai", "Adithya", "Content Developer");
emp ==> Name = Sai, Adithya | designation = Content Developer
คำสั่ง JShell ที่มีประโยชน์
| คำสั่ง | คำอธิบาย |
|---|---|
| /list | แสดง snippets ทั้งหมด |
| /list -all | รวม snippets ที่ล้มเหลว/overwritten |
| /vars | แสดง variables ทั้งหมด |
| /methods | แสดง methods ทั้งหมด |
| /types | แสดง classes/interfaces ทั้งหมด |
| /imports | แสดง imports ทั้งหมด |
| /edit | เปิด external editor |
| /save file.jsh | บันทึก session |
| /open file.jsh | โหลด session |
| /reset | reset session |
| /exit | ออกจาก JShell |
JShell Startup Scripts
- DEFAULT - import พื้นฐาน (java.io, java.util, java.net, etc.)
- JAVASE - import ทุก Java SE packages
- PRINTING - define print, println, printf methods
ใช้ด้วย jshell --startup <name> หรือ /set startup <name>