Search code examples
javaabstract-syntax-treeeclipse-jdt

How can I store values inside JDT/ASTVisitor()?


I have a code that detects the start position and length of invocation of a method in the source as follows.

I need to store those data outside the ASTVisitor(), but using final int, I got an error.

How can I store values inside ASTVisitor()?

public void setPositionFinder(String methodName) throws JavaModelException
{
    //findMethod(methodName);
    IType type = this.javaProject.findType(this.className);
    ICompilationUnit unit = type.getCompilationUnit();
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(unit);
    parser.setResolveBindings(true);
    CompilationUnit cunit = (CompilationUnit) parser.createAST(null);
    //ASTNode root = parser.createAST(null);

    final String name = this.newMethodName;
    final int startPosition = -1;
    final int length = -1;

    cunit.accept(new ASTVisitor() {
        public boolean visit(MethodInvocation methodInvocation)
        {
            String methodName = methodInvocation.getName().toString();
            System.out.println(methodName);
            if (methodName.equals(name))
            {
                // ERROR!
                startPosition = methodInvocation.getStartPosition();
                length = methodInvocation.getLength();
                System.out.printf("startPosition %d - Length %d", startPosition, length);       
            }
            return false;
        }
    });
}

enter image description here


Solution

  • Declare the starPosition and length variables as static member variables of the class. You can then access then from inside the ASTVisitor inner class. Changing the setPositionFinder method to static may also be preferred, so that it can be invoked in static way.