eclipse中给定一个ASTNode,有什么办法可以得到对应的源代码行号吗?
最佳答案
您可以获取 ASTNode
的行号使用下面的代码
int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
编译单元可以从
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);
然后你可以使用
ASTVisitor
使用以下代码访问所需节点类型(例如 MethodDeclaration 节点)的模式: compilationUnit.accept(new ASTVisitor() {
public boolean visit(MethodDeclaration node) {
int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
return true;
}
});
关于eclipse ASTNode 到源代码行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11126857/