使用JDT获取startPosition和方法调用的长度

时间:2013-01-17 02:59:42

标签: java eclipse eclipse-jdt

假设我有这个Java源代码。如何获取startPosition和“extractedMethod(amount)”调用的长度?

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

我可以使用hexa查看器来查找起始位置是0x1FA,长度是len(“extract(method)”)== 17,但我想用编程方式使用JDT。

一旦我可以获得CompilationUnit,但我需要知道如何在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(...)
});

2 个答案:

答案 0 :(得分:1)

您可以获取ASTNode的起始行号和长度,如下所示

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

有关详细信息,请参阅以下帖子

答案 1 :(得分:0)

这是适合我的代码。 - 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;
        }
    });
}