Eclipse从.java文件创建CompilationUnit [英] Eclipse create CompilationUnit from .java file

查看:218
本文介绍了Eclipse从.java文件创建CompilationUnit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆