问题
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