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

假设我有这个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; } .... } 

在此处输入图像描述

我可以使用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(...) }); 

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

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

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

  • eclipse ASTNode到源代码行号

  • 如何从java编译器树api生成注释生成的ast?

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