问题描述
我正在编写一个 Eclipse 插件,它使用 JDT AST 的 ASTParser
来解析一个方法.我正在寻找创建特定类型对象的方法.
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.
当我找到一个 ClassInstanceCreation
时,我会在其上调用 getType()
以查看正在实例化的类型.我想确定正在处理的完全解析类型是我认为的类型,所以我将生成的 Type
对象告诉 resolveBinding()
.即使没有编译错误并且即使我在 ASTParser
上调用了 setResolveBindings(true)
,我也会返回 null
.我给了我的 ASTParser
(通过 setSource()
)包含我的方法的 ICompilationUnit
,因此解析器可以访问整个工作区上下文.
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());
为什么 resolveBinding()
返回 null
?如何获取绑定信息?
Why does resolveBinding()
return null
? How can I get the binding information?
推荐答案
隐藏在 ASTParser.setKind() 概览的底部
,小心隐藏,不让人们排查问题 resolveBinding()
和setResolveBindings()
,就是语句
Tucked away at the bottom of the overview of ASTParser.setKind()
, carefully hidden from people troubleshooting resolveBinding()
and setResolveBindings()
, is the statement
仅当 kind
为 K_COMPILATION_UNIT
时才计算绑定信息.
(来自 在线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!
这篇关于为什么即使我在 ASTParser 上设置了 setResolveBindings(true),resolveBinding() 仍会返回 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!