Question

I've been implementing a Java parser with JDT and I can't figure out how to get a variable type when its node's type is VariableDeclarationFragment.

I found out how to get a variable type only when it comes to VariableDeclaration

My code is the following.

public boolean visit(VariableDeclarationFragment node) {
    SimpleName name = node.getName();

    System.out.println("Declaration of '" + name + "' of type '??');

    return false; // do not continue 
}

Can anyone help me?

Was it helpful?

Solution

I just figured out how to get the type from VariableDeclarationFragment. I just have to get its parent, which is a FieldDeclaration, then I can access its variable type.

OTHER TIPS

This may be not the best type-safety solution, but it worked for my case.
I'm simply extracting type which is being handled in node by calling toString() method.

    public boolean visit(VariableDeclarationFragment node) {
            SimpleName name = node.getName();
            String typeSimpleName = null;

            if(node.getParent() instanceof FieldDeclaration){
                FieldDeclaration declaration = ((FieldDeclaration) node.getParent());
                if(declaration.getType().isSimpleType()){
                    typeSimpleName = declaration.getType().toString();
                }
            }

            if(EXIT_NODES.contains(typeSimpleName)){
                System.out.println("Found expected type declaration under name "+ name);
            }

            return false;
    }

With help of checking type of node, and previous declaration of EXIT_NODE list of classes simple names, it gives me pretty much confidence that I'm at the right spot.

HTH a little.

According to the JDT API docs, VariableDeclarationFragment extends VariableDeclaration, so you can use the same methods to get the type for either one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top