1
votes

I need to get IField or IJavaElement references for all variables in my source code. I use plugin, get a ICompilationUnit from which I am able to read all top-level objects using:

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

or

for( IJavaElement i:unit.getAllTypes() )

How can I access local variables? I was trying to parse ICompilationUnit to CompilationUnit, where I can get an ASTNode of each field, but then I'm not able to transform it info an IField. Any ideas?

//edit: For example: For a class:

public class Test {

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

}

I call

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

And the output is:

itype class Test [in [Working copy] Test.java [in [in src [in testowy]]]] int global1 int global2 void a() iField int global1 [in Test [in [Working copy] Test.java [in [in src [in testowy]]]]] iField int global2 [in Test [in [Working copy] Test.java [in [in src [in testowy]]]]]

So no local variables were found...

//added - still struggling: Actually it's not the behavior I was expecting.

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++;
            }

        }

This code I've expected to find all methods (that works) and get all local variables from methods (that doesn't work). It never enters loop with fields. It prints function declaration correctly so I'm sure it sees all variables...

And as for using INodes, I can visit all nodes, but how can I change type from Node to IField/IJavaElement which I need?

Thanks :)

1

1 Answers

1
votes

If you just want to get the fields of a type you can do it like this:

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

However, if you want to find all variable declarations (both fields and local variables), you'd better use an ASTVisitor. This will visit your whole AST and you'll just have toimplement the visit methods for the desired AST elements, in your case I guess it would be the VariableDeclarationFragment's.