Search code examples
javaabstract-syntax-treeeclipse-jdt

Get the type of a FieldDeclaration in AST


I am working with a Java AST. How can I get the Type (e.g. String or MyOwnType) of a FieldDeclaration or VariableDeclaration? In ASTView I can see it under SimpleName > type binding, but with getters I cannot reach the member. I tried the solution from FieldDeclaration to IField - Getting IBinding from FieldDeclaration but resolveBinding returns null when visiting the FieldDeclaration.

Why does resolveBinding() return null even though I setResolveBindings(true) on my ASTParser? not working either


Solution

  • Wow, this was tough. The last line made it possible to resolve the bindings and retrieve the type via varDeclFrag.resolveBinding().getType().getQualifiedName(); although I already thought I did the same in setEnvironment when referring to sources:

    String[] sources = { "C:\\a\\TheMightyExampleProject\\src" };
    String[] classPaths = { "C:\\a\\antlr-4.1-complete.jar" };
    
    parser.setEnvironment(classPaths, sources, new String[] { "UTF-8" }, true);
    parser.setBindingsRecovery(true);
    parser.setResolveBindings(true);
    parser.setCompilerOptions(options);
    parser.setStatementsRecovery(true);
    parser.setUnitName("C:\\a\\TheMightyExampleProject\\src"); // ftw
    

    You can also check out the answer of Ida bindings not resolving with AST processing in eclipse