javaeclipse-jdt

How to get line number for general ASTNode in the source code?


How can I implement this method in the basic class ASTNode so that I can obtain different ASTNode line number easier? For exampel, if I want to get MethodDeclaration location I need to write code

@Override
public boolean visit(MethodDeclaration node) {
    int lineNum = ((CompilationUnit) node.getRoot()).getLineNumber(node.getStartPosition());
    return super.visit(node);
}

However, I want to get location information like this

@Override
public boolean visit(MethodDeclaration node) {
    int lineNum = node.getLineNumber();
    return super.visit(node);
}

CompilationUnit provides a method called getLineNumber implemented with lineEndTable and general ASTNode only have a field named startPosition, so is it possible that I can obtain a lineEntTable in the abstract class ASTNode?


Solution

  • "Is it possible...?" No, individual nodes like MethodDeclaration don't have this information. In order to avoid redundancy lineEndTable is stored in only one particular node, the CompilationUnit. Given you have already found a solution there is no benefit in looking for another solution. The API is sufficient and the extra code you have to write is minimal.