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

Forward reference trong JShell Java 9 là gì?

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ạiVí dụHành vi
Variablevoid m() { System.out.println(x); } trước int x;Method tạo OK, gọi lỗi cho đến khi x khai báo
Methodvoid a() { b(); } trước void b() {}OK – method resolve tại runtime
Classvoid m() { new NotYetDefined(); }OK – class resolve khi gọi method
Return typeMyClass m() { return null; } trước class MyClass {}OK
Parameter typevoid 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 /list xem 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.