How to get method name from VariableDeclarationStatement
i have a variable of type VariableDeclarationStat开发者_开发问答ement. I want to get the name of the method from this variable . How can i do that?Help
You could use the code in this thread and use an VariableDeclarationFragment
:
public boolean visit(VariableDeclarationStatement node)
{
System.out.println("Visiting variable declaration statement.");
for(int i = 0; i < node.fragments().size(); ++i)
{
VariableDeclarationFragment frag = (VariableDeclarationFragment)node.fragments().get(i);
System.out.println("Fragment: " + node.getType() + " " + frag.getName());
}
System.out.println("");
return true;
}
To get the method in which this (variable) is defined, I would use a visitor of the CompilationUnit
, looking for that VariableDeclarationFragment
while memorizing the IMethod
I am currently parsing:
IJavaElement element = delta.getElement();
if(element.getElementType() != IJavaElement.COMPILATION_UNIT)
return;
ICompilationUnit compilationUnit = (ICompilationUnit)element;
try
{
IType type = compilationUnit.findPrimaryType();
IMethod[] methods = type.getMethods();
for(IMethod method : methods)
{
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(compilationUnit);
parser.setSourceRange(method.getSourceRange().getOffset(), method.getSourceRange().getLength());
//parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
//parser.setSource(method.getSource().toCharArray());
//parser.setProject(method.getJavaProject());
parser.setResolveBindings(true);
CompilationUnit cu = (CompilationUnit)parser.createAST(null);
cu.accept(new ASTMethodVisitor());
// If the visitor visit the right VariableDeclarationFragment,
// then the right IMethod is the current 'method' variable
}
}
catch(JavaModelException e)
{
e.printStackTrace();
}
精彩评论