2

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

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;
    }
    ....
}

在此处输入图像描述

我可以使用六角查看器来查找起始位置为 0x1FA,长度为 len("extracted(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(...)
});
4

2 回答 2

1

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

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

有关更多信息,请参阅以下帖子

于 2013-01-17T03:58:44.057 回答
0

这是对我有用的代码。-如何在 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;
        }
    });
}
于 2013-01-17T12:59:19.893 回答