Why does resolveBinding() return null even though I setResolveBindings(true) on my ASTParser?
Asked Answered
D

1

7

I am writing an Eclipse plug-in that uses JDT AST's ASTParser to parse a method. I am looking within that method for the creation of a particular type of object.

When I find a ClassInstanceCreation, I call getType() on it to see what type is being instantiated. I want to be sure that the fully-resolved type being dealt with there is the one I think it is, so I tell the resultant Type object to resolveBinding(). I get null back even though there are no compilation errors and even though I called setResolveBindings(true) on my ASTParser. I gave my ASTParser (via setSource()) the ICompilationUnit that contains my method, so the parser has access to the entire workspace context.

final IMethod method = ...;
final ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setResolveBindings(true);
parser.setSource(method.getCompilationUnit());
parser.setSourceRange(method.getSourceRange().getOffset(), method.getSourceRange().getLength());
parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
final TypeDeclaration astRoot = (TypeDeclaration) parser.createAST(null);
final ClassInstanceCreation classInstanceCreation = walkAstAndFindMyExpression(astRoot);
final Type instantiatedType = classInstanceCreation.getType();
System.out.println("BINDING: " + instantiatedType.resolveBinding());

Why does resolveBinding() return null? How can I get the binding information?

Diaphanous answered 13/4, 2010 at 18:9 Comment(0)
D
7

Tucked away at the bottom of the overview of ASTParser.setKind(), carefully hidden from people troubleshooting resolveBinding() and setResolveBindings(), is the statement

Binding information is only computed when kind is K_COMPILATION_UNIT.

(from the online Javadoc)

I don't understand offhand why this would be the case, but it does seem to point pretty clearly at what needs to be different!

Diaphanous answered 13/4, 2010 at 18:14 Comment(2)
I have a similar case where the kind is K_COMPILATION_UNIT but still resolveBinding() returns null. Any idea why?Fanchan
Just a late comment on "why this would be the case": if you parse anything smaller than a compilation unit then you have no import statements, and hence binding resolution is likely to fail.Chalk

© 2022 - 2024 — McMap. All rights reserved.