假设我有这个 Java 源代码。如何获取“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;
}
....
}
我可以使用 hexa 查看器来查找起始位置为 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(...)
});
最佳答案
您可以获取 ASTNode 的起始行号和长度,如下所示
int startLineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
int nodeLength = node.getLength();
int endLineNumber = compilationUnit.getLineNumber(node.getStartPosition() + nodeLength) - 1;
请参阅以下帖子了解更多信息
关于java - 使用 JDT 获取方法调用的起始位置和长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14371526/