我有一个 CompilationUnit
,其中包含一个未导入对另一个类的引用的类。
Eclipse 轻松解决了此类问题,并建议导入缺少的类(位于父包中)。
如何在不知道其名称或位置的情况下以编程方式导入丢失的类,以便在生成的 Java 类源文件中,导入显示为:import com.foobar.missingclass
。
谢谢。
编辑 1: 回应一些评论:反射、注入(inject)、ClassLoader 和其他运行时机制不是正确的选择,因为我正在通过 Eclipse JDT API 静态处理类。 拜托,我只是在寻找面向静态的解决方案。
仅供引用:这是我们如何列出 CompilationUnit
中的 imports
:
List<ImportDeclaration> existingImports = aCompilationUnit.imports();
问题是我不知道如何生成缺少的 ImportDeclaration
。
谢谢。
最佳答案
引用我自己的 answer in the JDT forum :
For manipulating the imports of a Java file please see class org.eclipse.jdt.core.dom.rewrite.ImportRewrite: the javadoc outlines its usage.
If all you have is an unresolvable simple name, utilities like ASTResolving.guessBindingForTypeReference(node) come in handy.
If that doesn't work for you, you may have to use the org.eclipse.jdt.core.search.SearchEngine and somehow cope with potentially many matches for a given simple name.
让我补充一下:如果创建 ImportDeclaration 是您唯一的问题,那么使用 aCompilationUnit.getAST().newImportDeclaration()
,但使用 ImportRewrite
的问题更多功能强大,因为它直接生成更新文件所需的 TextEdit
。
关于Java : Import a class programmatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31572602/