java - 使用 eclipse AST 检查 Java 代码片段

标签 java eclipse syntax abstract-syntax-tree

我正在尝试使用 Eclipse 抽象语法树检查一些 Java 代码片段的语法和逻辑正确性。

我做了一些关于如何做到这一点的研究,我阅读了文档,但我还没有找到一个明确的例子。

所以,我想检查一组语句的正确性,例如:

System.out.println("I'm doing something");
callAMethod(7);
 System.out.println("I'm done");**sdsds**

类似的东西。你明白了。在这里,sdsds 应该被标记为错误。

我的问题是如何检测 Java 文本在句法或词法上是否不正确?我怎样才能得到描述错误的消息?

我的代码是:

ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_STATEMENTS);
parser.setSource(textToParse.toCharArray());
parser.setResolveBindings(false); 
ASTNode node = (ASTNode) parser.createAST(null); 
 // If MALFORMED bit is 1, then we have an error. The position of MALFORMED 
 being 1, then this should detect the error. **But it doesn't. What's the problem?**
    if (node.getFlags() % 2 == 1) { 
    // error detected
}

if (node instanceof CompilationUnit) {
    // there are severe parsing errors (unrecognized characters for example)
    if (((CompilationUnit) node).getProblems().length != 0) {
        // error detected
    }
}

希望有人能帮助我。非常感谢!

最佳答案

如果将解析器类型更改为 K_COMPILATION_UNIT 并调用解析器,则可以向返回的编译单元询问问题。

    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    IProblem[] problems = cu.getProblems();
    for(IProblem problem : problems) {
        System.out.println("problem: " + problem.getMessage() + problem.getSourceStart());
    }

关于java - 使用 eclipse AST 检查 Java 代码片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5769730/

相关文章:

java - 在 Eclipse 中,构建 Android 应用程序时,我以某种方式删除了 "R"类,并且无法让 Eclipse 再次生成它

javascript - "for"开头的分号是如何工作的?

c++ - 在 C++ 中通过引用传递对象

ruby - 为什么 f(arg, superfluous_arg) 是 ArgumentError 而 f (arg, superfluous_arg) 是 SyntaxError?

java - JLabel 内的两行文本

java - 我可以在 swing 中使用单个布局管理器实例吗?

java - 一种在 Eclipse 中按部分包定义搜索的方法?

java - 我可以为枚举中的每个值添加一个 JRadioButton 吗?

Eclipse IDE 问题 "not win32 application"

android - Google Play 服务库未安装