问题
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;
}
....
}
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(...)
});
回答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
eclipse ASTNode to source code line number
How to access comments from the java compiler tree api generated ast?
回答2:
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;
}
});
}
来源:https://stackoverflow.com/questions/14371526/getting-startposition-and-length-of-a-method-invocation-using-jdt