JShell (command-line tool Java 9) cho phép nhập statement Java, evaluate, in kết quả. Forward reference là tham chiếu đến method, variable, class chưa tồn tại trong code đã nhập. Do JShell evaluate tuần tự, forward reference tạm thời unresolved.
JShell hỗ trợ forward reference trong: method bodies, return types, parameter types, variable types, within a class.
Ví dụ: Forward reference variable
C:\Users\User> jshell
| Welcome to JShell -- Version 9.0.4
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
Khai báo variable sau đó
jshell> String notYetDeclared = "variable is declared" notYetDeclared ==> "variable is declared" jshell> forwardReference() variable is declared
Các loại forward reference
| Loại | Ví dụ | Hành vi |
|---|---|---|
| Variable | void m() { System.out.println(x); } trước int x; | Method tạo OK, gọi lỗi cho đến khi x khai báo |
| Method | void a() { b(); } trước void b() {} | OK – method resolve tại runtime |
| Class | void m() { new NotYetDefined(); } | OK – class resolve khi gọi method |
| Return type | MyClass m() { return null; } trước class MyClass {} | OK |
| Parameter type | void m(MyClass c) {} trước class MyClass {} | OK |
Lợi ích
- Cho phép định nghĩa method theo thứ tự logic (top-down) chứ không phải bottom-up.
- Hỗ trợ recursive method:
int fact(int n) { return n<=1?1:n*fact(n-1); }. - Tương tự forward declaration trong C/C++ nhưng tự động resolve.
Lưu ý
- Variable forward reference: method không thể invoke cho đến khi variable khai báo.
- Class/Method forward reference: resolve khi thực thi (runtime), không phải compile-time.
- Dùng
/listxem trạng thái snippet (có marker forward reference).
Forward reference làm JShell linh hoạt cho exploratory programming – viết code theo tư duy tự nhiên.