Java 9 的 JShell 中什麼是前向引用?
JShell 是一個命令列工具,允許我們輸入 Java 語句(簡單語句、複合語句,甚至是完整的 方法和類),對其進行評估並列印結果。
前向引用是指引用我們尚未在 JShell 中鍵入的任何程式碼中的方法、變數或類的命令。由於程式碼在 JShell 中順序輸入和評估,這些前向引用暫時未解析。JShell 支援在方法體、返回型別、引數型別、變數型別和類內部使用前向引用。
在下面的程式碼片段中,我們在 Jshell 中建立了一個方法forwardReference()。在宣告變數之前,無法呼叫此方法。如果嘗試呼叫此方法,則會顯示警告訊息:“嘗試呼叫方法 forwardReference(),但在宣告變數 notYetDeclared 之前無法呼叫”
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在下面的程式碼片段中,我們聲明瞭返回字串的“notYetDeclared”變數。最後,如果我們在 JShell 中呼叫forwardReference(),則會列印“變數已宣告”。
jshell> String notYetDeclared = "variable is declared" notYetDeclared ==> "variable is declared" jshell> forwardReference() variable is declared
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP