有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在JShell中,如何评估整个java代码?

我正在使用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);

经过计算,我在输出片段中看到了错误

cannot find symbol
  symbol:   method hello()
  location: class 

这里有什么问题


共 (1) 个答案

  1. # 1 楼答案

    eval不是为处理这样的代码而设计的。你展示的代码实际上是两个“完整的片段”,在你进入eval之前需要分解。从docs开始:

    The input should be exactly one complete snippet of source code, that is, one expression, statement, variable declaration, method declaration, class declaration, or import. To break arbitrary input into individual complete snippets, use SourceCodeAnalysis.analyzeCompletion(String).

    “real”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)));
    

    你会得到:

    Invalid method declaration; return type required

    这正是在类级别进行方法调用时得到的错误消息

    无论如何,要使代码正常工作,只需首先eval方法声明,然后eval调用hello();