[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [Newsgroup Home]
[news.eclipse.tools.jdt] Re: AST visitor

Jing Xie wrote:
David Wegener wrote:
Jing Xie wrote:
Hello Everyone,

I ran into a problem which drove me crazy.

I was trying to traverse an AST of a java file to print out the line information of all the MethodInvocation nodes. I subclass the ASTVisitor for the MethodInvocation node like this:

public class MethodInvocationVisitor extends ASTVisitor{
       public boolean visit (MethodInvocation node){
               int line = node.getStartPosition();
               System.out.println("Visiting: " + line + "; " + node);
               return false;
             }
}

The java file for the AST is pretty simple (doesn't make much sense, but that's what I need):

import javax.servlet.http.*;
public class HelloWorld {
static HttpServletRequest request = null;
/**
* @param args
*/
public static void main(String[] args) {
String contentType; String username = request.getParameter("username");
contentType = request.getContentType();
printName(username);
printName(contentType);
}
public static void printName(String username){
request.setAttribute("username",request.getAttribute(username));
System.out.println(username);
}


}

The total line number showed in the editor is only 21.
But the console output looks like this:
Visiting: 218; request.getParameter("username")
Visiting: 269; request.getContentType()
Visiting: 304; printName(username)
Visiting: 334; printName(contentType)
Visiting: 417; request.setAttribute("username",request.getAttribute(username))
Visiting: 485; System.out.println(username)


This is ridiculously wrong, but I have no idea where to check, since this is really simple, I was just following the tutorials I found on the Internet.

I'd appreciate if someone can pinpoint the root cause of this problem.

Thanks.
Jing

You seem to have missed that getStartPosition returns the character index and not the line index. The output looks accurate for a character index based on a quick look at your target source.
Thanks for you reply. But then how can I get the line number of the node I am visiting?

Jing

Sorry to reply to my own post. I just figured out the way to get the line number of a ASTNode:


int lineNumber = CompilationUnit.getLineNumber(node.getStartPosition());

Just in case some one else needs it.

Thanks.
Jing