JShell เป็น command-line tool ให้ป้อน Java statements (simple, compound, methods, classes) ประเมินและพิมพ์ผลลัพธ์
Forward references คือคำสั่งที่อ้างอิงถึง methods variables หรือ classes ที่ยังไม่มีอยู่ในโค้ดที่พิมพ์ใน JShell เนื่องจากโค้ดถูกป้อนและประเมินตามลำดับ forward references จึง unresolved ชั่วคราว JShell รองรับ forward references ใน method bodies return types parameter types variable types และ within a class
ตัวอย่าง: Forward Reference ใน Method Body
C:\Users\User>jshell
| Welcome to JShell -- Version 9.0.4
| For an introduction type: /help intro
jshell> void forwardReference() {
...> System.out.println(notYetDeclared);
...> }
| created method forwardReference(), however, it cannot be invoked until variable notYetDeclared is declared
jshell> forwardReference()
| attempted to call method forwardReference() which cannot be invoked until variable notYetDeclared is declared
หลังประกาศตัวแปรแล้ว
jshell> String notYetDeclared = "variable is declared"
notYetDeclared ==> "variable is declared"
jshell> forwardReference()
variable is declared
Forward Reference ในที่อื่น
Return Type
jshell> MyClass myMethod() { return new MyClass(); }
| created method myMethod(), however, it cannot be invoked until class MyClass is declared
jshell> class MyClass { }
| created class MyClass
jshell> myMethod()
myMethod ==> MyClass@...
Parameter Type
jshell> void paramType(MyClass mc) { }
| created method paramType(), however, it cannot be invoked until class MyClass is declared
Variable Type
jshell> MyClass myVar;
| created variable myVar, however, it cannot be used until class MyClass is declared
Within a Class
jshell> class Outer {
...> Inner inner; // forward reference to Inner
...> class Inner { }
...> }
| created class Outer
คำสั่งที่เกี่ยวข้อง
- /list - แสดงสนิปเพททั้งหมด (forward references จะมีเครื่องหมาย)
- /list -all - แสดงรวม unresolved snippets
- /drop <id> - ลบสนิปเพทที่มีปัญหา
Forward references ทำให้เขียนโค้ดแบบ top-down ได้ ไม่ต้องประกาศทุกอย่างก่อนใช้งานเหมือน Java ทั่วไป