eclipse ASTNode to source code line number

帅比萌擦擦* 提交于 2019-12-07 08:23:42

问题


Given an ASTNode in eclipse, is there any way to get the corresponding source code line number?


回答1:


You can get the line number of an ASTNode using the below code

    int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;

the compilation unit can be obtained from the ASTParser using the below code

    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);

Then you can use the ASTVisitor pattern to visit the type of required node (say MethodDeclaration node) using the below code:

    compilationUnit.accept(new ASTVisitor() {

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



回答2:


ASTNode has getStartPosition() and getLength() methods which deal with character offsets. To convert from a character offset to a line number you should use CompilationUnit's getLineNumber() method. CompilationUnit is the root of your AST tree.




回答3:


Apart from the general solution that has already been described, there is another one that applies if you need the line number of an ASTNode including leading whitespaces or potential comments written in front of the ASTNode. Then you can use:

int lineNumber = compilationUnit.getLineNumber(compilationUnit.getExtendedStartPosition(astNode))

See the API:

Returns the extended start position of the given node. Unlike ASTNode.getStartPosition() and ASTNode.getLength(), the extended source range may include comments and whitespace immediately before or after the normal source range for the node.



来源:https://stackoverflow.com/questions/11126857/eclipse-astnode-to-source-code-line-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!