Java JDT parser. Get variable type of VariableDeclarationFragment

女生的网名这么多〃 提交于 2019-12-11 02:40:04

问题


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?


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/18454697/java-jdt-parser-get-variable-type-of-variabledeclarationfragment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!