Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse create CompilationUnit from .java file

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.

like image 870
bellpeace Avatar asked Jun 23 '12 04:06

bellpeace


1 Answers

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.

like image 178
Unni Kris Avatar answered Oct 01 '22 22:10

Unni Kris