2

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(...)
});
prosseek
  • 182,215
  • 215
  • 566
  • 871

2 Answers2

1

You can get the start line number and length of a ASTNode as below

int startLineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
int nodeLength = node.getLength();
int endLineNumber = compilationUnit.getLineNumber(node.getStartPosition() + nodeLength) - 1;

See the below posts for more information

Community
  • 1
  • 1
Unni Kris
  • 3,081
  • 4
  • 35
  • 57
0

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;
        }
    });
}
Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871