Eclipse从.java文件创建CompilationUnit [英] Eclipse create CompilationUnit from .java file
问题描述
如何将.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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!