2
我有一个VariableDeclarationStatement类型的变量。我想从这个变量中获取方法的名称。我该怎么做,帮助如何从VariableDeclarationStatement获取方法名称
我有一个VariableDeclarationStatement类型的变量。我想从这个变量中获取方法的名称。我该怎么做,帮助如何从VariableDeclarationStatement获取方法名称
你可以在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();
}
但是,这将使该变量的名字和类型。我想要的方法名也是这样的: – Steven 2010-02-26 05:36:12
@Nishan:刚刚添加了访问者策略来查找定义了'VariableDeclarationStatement'的'IMethod'。 – VonC 2010-02-26 06:51:26
我没有得到它。任何链接oe例如请 – Steven 2010-02-26 08:26:10