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

更新於:2020年3月5日

254 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.