如何使用Eclipse JDT中的代码查找方法中是否使用了成员变量? [英] How to find whether a member variable is used in a method using code in eclipse jdt?

查看:136
本文介绍了如何使用Eclipse JDT中的代码查找方法中是否使用了成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在使用特定成员变量的类中找到所有方法。 (例如eclipse中的 References,但我想使用代码实现...)我使用访问FieldDeclaration的AST访问者模式来获取所有成员变量的名称和类型。我还使用访问者模式来访问MethodDeclaration节点,以使用getBody()获取每个方法的内容。现在,我有了字段变量名称,类型和成员方法的详细信息。我以为可以在每个成员方法的内容上使用字符串搜索,但是对于变量名 a,对于 class之类的关键字以及其他关键字,搜索都可能返回true!有没有办法找到对应于fieldDeclaration的特定变量的用法? (例如Binding之类的东西?)如果是这样,什么是AST节点或类?

I have to find all the methods in a class that use a particular member variable. (like "References" in eclipse but I want to implement using code...)I use AST visitor pattern that visits FieldDeclaration to get the name and type of all the member variables. I also use visitor pattern that visits MethodDeclaration nodes to get the content of each method using getBody(). Now I have the field variable name, type and member method details. I thought I can use a string search on the content of each member method but for a variable name "a", search may return true for keywords like "class" and others too!!! Is there a way to find the usage of a particular variable corresponding to a fieldDeclaration?? (like Binding or something??) If so, what is the AST Node or Class?

这是我使用的代码...

Here's the code I used...

 SimpleNameVisitor simpleNameVisitor=new SimpleNameVisitor();
 //SimpleNameVisitor is the visitor pattern for SimpleName
 simpleNameVisitor.process(mthd.getMethodBlock());
 //mthd is the object that stores method details
 for(SimpleName simpName:simpleNameVisitor.getIdentifiers()){
    if(varName.contentEquals(simpName.getFullyQualifiedName())){
        //varName is the field variable name
        System.out.println("MethodName: "+mthd.getName());
        return;
    }
  }

这是解决问题的代码(由wjans建议) ;更改等于contentEquals)

Here's the code that solved the problem(suggested by wjans;changed equals to contentEquals)

VariableDeclarationFragment fragment = ... ;
IBinding binding = fragment.getName().resolveBinding();


public boolean visitNode(SimpleName simpleName) throws Exception {
if (binding.toString().contentEquals(simpleName.resolveBinding().toString()) {
    ....
}

}

推荐答案

您可以执行以下操作:

保留对FieldDeclaration绑定的引用,

Keep a reference to the binding of your FieldDeclaration,

VariableDeclarationFragment fragment = ... ;
IBinding binding = fragment.getName().resolveBinding();

,并在访问MethodDeclaration内的SimpleName时使用它与绑定进行比较

and use this to compare it with the bindings when visiting SimpleName's inside your MethodDeclaration

public boolean visitNode(SimpleName simpleName) throws Exception {
    if (binding.equals(simpleName.resolveBinding()) {
        ....
    }
}   

这篇关于如何使用Eclipse JDT中的代码查找方法中是否使用了成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆