Search code examples
javaeclipseeclipse-jdt

Getting startPosition and length of a method invocation using JDT


Let's say I have this Java source code. How can I get the startPosition and length of "extractedMethod(amount)" invocation?

package smcho;

public class Extract {
String _name = "";

public int extractedMethod(int amount)
{
    ....
}

public int getValue(int amount) {
    if (amount > 10) {
    int z = extractedMethod(amount);
    return z;
    }
    ....
}

enter image description here

I could use hexa viewers to find the start position is 0x1FA and the length is len("extracted(method)") == 17, but I'd like to do it programmatically using JDT.

Once I could get the CompilationUnit, but I need to know how to get the invocation reference in that CompilationUnit.

IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject orig = root.getProject(this.projectName);
orig.open(pm);
javaProject = JavaCore.create(orig);
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);

root.accept(new ASTVisitor() {
    public bool visit(...)
});

Solution

  • This is the code that works for me. - How can I store values inside JDT/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;
    
        cunit.accept(new ASTVisitor() {
            public boolean visit(MethodInvocation methodInvocation)
            {
                String methodName = methodInvocation.getName().toString();
                System.out.println(methodName);
                if (methodName.equals(name))
                {
                    startPosition = methodInvocation.getStartPosition();
                    length = methodInvocation.getLength();
                    System.out.printf("startPosition %d - Length %d", startPosition, length);       
                }
                return false;
            }
        });
    }