Java 9 中 JShell 中的前向引用是什么?
javaobject oriented programmingprogramming
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