java - 使用类型绑定(bind)创建编译单元

标签 java eclipse-plugin abstract-syntax-tree eclipse-jdt

我正在使用 AST API在 Java 中,我正在尝试创建一个 Compilation Unit与类型绑定(bind)。我写了下面的代码:

private static CompilationUnit parse(ICompilationUnit unit) {
 ASTParser parser = ASTParser.newParser(AST.JLS3);
 parser.setKind(ASTParser.K_COMPILATION_UNIT);
 parser.setSource(unit);
 parser.setResolveBindings(true);
 CompilationUnit compiUnit = (CompilationUnit) parser.createAST(null);
 return compiUnit;
}

不幸的是,当我在 Debug模式下运行此代码并检查 compiUnit 时,我发现 compiUnit.ast.resolver.isRecoveringBindings 为 false。
有谁能想出为什么它不是我指定的 true 的原因吗?
谢谢

最佳答案

您混淆了 API 的两个部分:绑定(bind)解析和绑定(bind)恢复。来自 setBindingsRecovery 的 JavaDoc:

void org.eclipse.jdt.core.dom.ASTParser.setBindingsRecovery(boolean enabled)

Requests that the compiler should perform bindings recovery. When bindings recovery is enabled the compiler returns incomplete bindings.

Default to false.

This should be set to true only if bindings are resolved. It has no effect if there is no binding resolution.

Parameters:
enabled true if incomplete bindings are expected, and false if only complete bindings are expected.

所以,是的。绑定(bind)恢复应该设置为 false,因为这是默认设置。但是,由于您显式设置了要解析的绑定(bind),因此应该在 AST 对象中将其设置为 true。您应该检查方法 AST.hasBindingsResolved() 以查看是否可以获得绑定(bind)。

要清楚:绑定(bind)解析是关于让解析器/编译器在创建 AST 时计算类型绑定(bind),而绑定(bind)恢复是关于使绑定(bind)能够被部分计算。老实说,我不太确定绑定(bind)恢复有什么帮助,但我相当确定这不是您需要的东西。

关于java - 使用类型绑定(bind)创建编译单元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4697614/

相关文章:

java - 将线程用于 100 个独立的小型本地搜索作业是否是一种干净的方法?

java - 从Java(然后是Eclipse)运行Maven,Gradle或其他基于批处理的脚本

java - 连接到 Eclipse 构建过程?

java - 是否可以使用 RCP Updatesite 将 Eclipse RCP 应用程序更新为新的 Eclipse

Python 最佳实践 : Abstract Syntax Trees

python-3.x - 使用 Python 遍历 Clang AST

Haskell Labeled AST : No instance for (Show1 (Label a)), 如何构建实例?

java - 将 Nashorn 与其他 Web 应用程序框架一起使用

java - 如何检查 Java 应用程序中 CPU 总是上升的原因?

java - 多线程客户端/服务器应用程序java问题