hi, i have a variable of type VariableDeclarationStatement. I want to get the name of the method from this variable . How can i do that?Help
+3
A:
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();
}
VonC
2010-02-26 05:16:57
but that will give the variable name and its type. I want the method name too in which it is declared
Steven
2010-02-26 05:36:12
@Nishan: just added the Visitor strategy to find the `IMethod` in which a `VariableDeclarationStatement` is defined.
VonC
2010-02-26 06:51:26
i didnt get it.Any link oe example please
Steven
2010-02-26 08:26:10
@Nishan: do you have a `CompilationUnit` instance? If yes, the thread I mentioned is a good example. If not, please edit your question and add the code you have to get a `VariableDeclarationStatement`. From that, I will be able to find a more relevant example.
VonC
2010-02-26 08:35:25
@VonC:thanks got it.I somehow had missed it
Steven
2010-02-26 09:08:24