[英]In JShell, How to evaluate whole java code?
我正在使用 JShell API 來運行 Java 代碼。 但是,當我運行整個代碼時出現錯誤。
例如:
import jdk.jshell.JShell;
var code= """
void hello(){
System.out.println("Hello world");
}
hello();
""";
JShell shell = JShell.create();
List<SnippetEvent> snippets = shell.eval(code);
評估后,我在 output 片段中看到錯誤。
cannot find symbol
symbol: method hello()
location: class
這里有什么問題?
eval
不是為處理這樣的代碼而設計的。 您顯示的代碼實際上是 2 個“完整片段”,在您進入eval
之前需要將其分解。 從文檔:
輸入應該是完整的源代碼片段,即一個表達式、語句、變量聲明、方法聲明、class 聲明或導入。 要將任意輸入分解為單獨的完整片段,請使用
SourceCodeAnalysis.analyzeCompletion(String)
。
“真正的”JShell 命令行程序可能使用SourceCodeAnalysis.analyzeCompletion(String)
方法將您的輸入分解為兩個完整的片段,並將每個片段傳遞給eval
。
以下是如何使用SourceCodeAnalysis.analyzeCompletion(String)
:
var code = "...";
JShell jshell = JShell.create();
SourceCodeAnalysis.CompletionInfo completionInfo = jshell.sourceCodeAnalysis().analyzeCompletion(code);
// this is the shortest complete code
System.out.println(completionInfo.source());
// this is what remains after removing the shortest complete code
// you'd probably want to analyze the completion of this recursively
System.out.println(completionInfo.remaining());
hello();
由於同樣的原因無法編譯
class Foo {
void hello() {
}
hello();
}
不編譯。
如果您查看診斷:
JShell shell = JShell.create();
List<SnippetEvent> events = shell.eval(code);
shell.diagnostics(events.get(0).snippet()).forEach(x -> System.out.println(x.getMessage(Locale.ENGLISH)));
你得到:
無效的方法聲明; 需要返回類型
如果您將方法調用置於 class 級別,這就是您收到的確切錯誤消息。
無論如何,要使您的代碼正常工作,只需先eval
方法聲明,然后eval
hello();
稱呼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.