问题描述
如何将 .java 文件加载到 CompilationUnit 中?例如,假设我在当前项目中有一个 A.java 文件.我想将它加载到 CompilationUnit 中,然后将它传递给 ASTParser.仅将其作为纯文本加载不是一种选择,因为在这种情况下我似乎不会在 AST 中获取绑定信息.
How can I load a .java file into a CompilationUnit? For example, lets say I have a A.java file in my current project. I would like to load it into a CompilationUnit and then pass it to the ASTParser. It is not an option just to load it as a plain text since it seems that in that case I will not get the binding information in the AST.
推荐答案
您可以使用 jdt
和 eclipse core
库加载项目.
You can load the projects using jdt
and eclipse core
libraries.
使用以下代码可以加载工作区中的所有项目.
Using the following code you can load all the projects in the workspace.
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
// Get all projects in the workspace
IProject[] projects = root.getProjects();
然后你就可以得到包,进而得到 java 文件.
Then you can get packages and in turn the java files.
IPackageFragment[] packages = JavaCore.create(project).getPackageFragments();
IPackageFragment mypackage = packages.get(0); // implement your own logic to select package
ICompilationUnit unit = mypackage.getCompilationUnits();
然后你可以使用这个 ICompilationUnit 对象来获取 CompilationUnit
Then you can use this ICompilationUnit object for getting the CompilationUnit
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(unit);
parser.setResolveBindings(true);
CompilationUnit cUnit = parser.createAST(null);
这个 CompilationUnit 对象可以传递给 ASTParser.
This CompilationUnit object can be passed on to the ASTParser.
这篇关于Eclipse 从 .java 文件创建 CompilationUnit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!