开发者

how can i get variable in a function?

开发者 https://www.devze.com 2022-12-20 20:23 出处:网络
i am developing a plugin in which i search for a particular method.Now i want to display all the variable declared and used in it along with their 开发者_运维技巧types.How can i do that?method name is

i am developing a plugin in which i search for a particular method.Now i want to display all the variable declared and used in it along with their 开发者_运维技巧types.How can i do that?method name is of IMethod type.Help


If you have the CompilationUnit of that IMethod, you could use a ASTParser as 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());

Then you can use an 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;
  }
});


What you need is the Java reflection API. Have a look at this: link text


You can use reflection to get the types of all the parameters required by the method.

First reflect the method using Class, then use `Method.getParameterTypes()'.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号