IFields用于CompilationUnit中的所有变量

时间:2011-05-14 08:29:32

标签: java abstract-syntax-tree eclipse-jdt

我需要为源代码中的所有变量获取 IField或IJavaElement引用。我使用插件,获得一个ICompilationUnit,我可以使用它来读取所有顶级对象:

  

for(IJavaElement i:unit.getTypes()[0] .getChildren())

  

for(IJavaElement i:unit.getAllTypes())

如何访问本地变量?我试图将ICompilationUnit解析为CompilationUnit,其中<​​strong>我可以获得每个字段的ASTNode ,但是我无法将其转换为IField 。有什么想法吗?

//编辑: 例如: 对于一个班级:

  

公共课测试{

     

int global1; int global2; void a()   {             global1 = 4;             int local1;             int local2 = 5; }

     

}

我打电话

  

for(IType type:unit.getTypes()){                 System.out.println(“itype”+ type);                 for(IField iField:type.getFields()){                     System.out.println(“iField”+ iField);   }}

输出是:

  

itype类测试[在[工作副本]   Test.java [in [in src [in   testowy]]]] int global1 int   global2 void a()iField int global1   [在Test [in [Working copy] Test.java中   [在[in src [in testowy]]]]]   iField int global2 [in Test [in   [工作副本] Test.java [in   [在src [in testowy]]]]]

所以没有发现局部变量......

//添加 - 仍在努力: 实际上这不是我期待的行为。

for( IMethod i:unit.getAllTypes()[0].getMethods() )
        {
        System.out.println("index to h:"+h+" type "+i.getSource()+" name: "+i.getElementName());
        h++;
        int o =0;
        for( IJavaElement j: i.getChildren() )
            {
                System.out.println("index to o: "+o+j+" type "+j.getElementType()+" name: "+j.getElementName());
                o++;
            }

        }

这段代码我期望找到所有方法(有效)并从方法中获取所有局部变量(这不起作用)。它永远不会进入带字段的循环。它正确打印函数声明,所以我确定它会看到所有变量...

至于使用INOD,我可以访问所有节点,但是如何将类型从Node更改为我需要的IField / IJavaElement?

谢谢:)

1 个答案:

答案 0 :(得分:1)

如果您只想获取某个类型的字段,可以这样做:

for (IType type : iCompilationUnit.getTypes()) {
    for (IField iField : type.getFields()) {
        ....
    }
}

但是,如果要查找所有变量声明(字段和局部变量),最好使用ASTVisitor。这将访问你的整个AST,你只需要实现所需AST元素的访问方法,在你的情况下我想它将是VariableDeclarationFragment