我有一个VariableDeclarationStatement类型的变量。我想从这个变量中获取方法的名称。我该怎么做?帮助
答案 0 :(得分:3)
您可以使用this thread中的代码并使用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;
}
为了获得定义此(变量)的方法,我将使用CompilationUnit
的访问者,在记忆我正在解析的VariableDeclarationFragment
时查找IMethod
:
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();
}