eclipse ASTNode到源代码行号

bra*_*ray 4 eclipse abstract-syntax-tree eclipse-jdt

给定eclipse中的ASTNode,有没有办法获得相应的源代码行号?

Unn*_*ris 16

您可以ASTNode使用以下代码获取a的行号

    int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
Run Code Online (Sandbox Code Playgroud)

编译单元可以从ASTParser使用下面的代码获得

    ASTParser parser = ASTParser.newParser(AST.JLS3);

    // Parse the class as a compilation unit.
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(source); // give your java source here as char array
    parser.setResolveBindings(true);

    // Return the compiled class as a compilation unit
    CompilationUnit compilationUnit = parser.createAST(null);
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用该ASTVisitor模式使用以下代码访问所需节点的类型(比如MethodDeclaration节点):

    compilationUnit.accept(new ASTVisitor() {

        public boolean visit(MethodDeclaration node) {       
            int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
            return true;
        }
    });
Run Code Online (Sandbox Code Playgroud)


Kon*_*hik 1

ASTNode 有 getStartPosition() 和 getLength() 方法来处理字符偏移量。要将字符偏移量转换为行号,您应该使用 CompilationUnit 的 getLineNumber() 方法。CompilationUnit 是 AST 树的根。