简体   繁体   中英

how to get the fully qualified name of node in an AST?

I'm using the ASTParser to parse some code and I need the fully qualified name of nodes. I tried the following and it is not working. It still gives me the simple name only.

public static void parse(String str)
{
 ASTParser parser = ASTParser.newParser(AST.JLS8);
 parser.setSource(str.toCharArray());


 parser.setResolveBindings(true);
 parser.setKind(ASTParser.K_COMPILATION_UNIT);
 parser.setBindingsRecovery(true);


 Map options = JavaCore.getOptions();
 JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
 parser.setCompilerOptions(options);

 CompilationUnit cu = (CompilationUnit) parser.createAST(null);

 cu.accept(new ASTVisitor() {

    public boolean visit(TypeDeclaration node) {

        System.out.println(node.getName().getFullyQualifiedName());
        return true;
    }

Any thoughts? Thanks!

Type org.eclipse.jdt.core.dom.Name is part of the AST structure and thus only knows about what's written in source code. If source code contains a simple name, that will be what this node contains.

To get the qualified name of the resolved type you need to request a binding using one of

  • org.eclipse.jdt.core.dom.AbstractTypeDeclaration.resolveBinding()
  • org.eclipse.jdt.core.dom.Name.resolveBinding()
  • ...

On the resulting ITypeBinding , getQualifiedName() should yield the name you are looking for.

I see that you already call parser.setResolveBindings(true); so you should be all set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM