我怎样才能在函数中得到变量?

时间:2010-02-19 08:37:19

标签: java eclipse-plugin

我正在开发一个插件,我在其中搜索特定的方法。现在我想要显示声明和使用的所有变量及其类型。我怎么能这样做?方法名称是IMethod类型。帮助< / p>

3 个答案:

答案 0 :(得分:1)

您需要的是Java反射API。看看这个:link text

答案 1 :(得分:1)

如果您拥有该IMethod的CompilationUnit,则可以使用ASTParser作为illustrated here):

ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(compilationUnit);
parser.setSourceRange(method.getSourceRange().getOffset(), method.getSourceRange().getLength());
parser.setResolveBindings(true);
CompilationUnit cu = (CompilationUnit)parser.createAST(null);
cu.accept(new ASTMethodVisitor());

然后您可以使用 ASTVisitor

cu.accept(new ASTVisitor() {
  public boolean visit(SimpleName node) {
    System.out.println(node); // print all simple names in compilation unit. in our example it would be A, i, j (class name, and then variables)
    // filter the variables here
    return true;
  }
});

答案 2 :(得分:0)

您可以使用反射来获取方法所需的所有参数的类型。

首先使用Class反映方法,然后使用`Method.getParameterTypes()'。

相关问题