Eclipse create CompilationUnit from .java file

怎甘沉沦 提交于 2019-11-27 15:42:14

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();

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();

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);

This CompilationUnit object can be passed on to the ASTParser.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!