Given an ASTNode in eclipse, is there any way to get the corresponding source code line number?
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;
}
});
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With